【问题标题】:Select everything but a specific data set选择除特定数据集以外的所有内容
【发布时间】:2016-11-25 06:53:12
【问题描述】:

我需要选择除我悬停的数据集以外的所有内容,到目前为止,我已经拥有它,所以没有选择 this,但现在我需要选择它,所以 this 并且没有选择具有公共数据集的所有内容

.on("mouseover", function(d) {
    console.log(d);
    var circleUnderMouse = this;
    d3.selectAll(".dot").filter(function(d,i) {
        return (this !== circleUnderMouse);
    })
})

【问题讨论】:

  • 你可以使用 :not 选择器 d3.select("svg").selectAll("*:not(.dot)");将 svg 替换为 ur rtto 元素

标签: javascript select d3.js mouseover selectall


【解决方案1】:

您可以只使用datum 参数,而不是使用this

当您将鼠标悬停在节点上时...

将为每个选定的元素评估指定的侦听器,传递当前数据 (d)、当前索引 (i) 和当前组(节点),并将 this 作为当前 DOM 元素。

因此,要查找具有相同数据的所有其他元素,您可以只使用第一个参数,它包含 datum,而不是 this,它是 DOM 元素.

这是一个演示给你看。我们有一个包含位置的数据集和一个名为 type 的键:

var data = [{type: "foo", x: 30, y: 90},
    {type: "foo", x: 10, y: 50},
    //etc...
];

将鼠标悬停在一个圆圈上,我们将选择所有其他与 type 属性值不同的圆圈,使它们消失:

circles.on("mouseover", function(d) {
    var filtered = circles.filter(function(e) {
        return e.type != d.type
    });
    filtered.attr("opacity", 0);
})

这里是演示:

var svg = d3.select("svg");
var data = [{
    type: "foo",
    x: 30,
    y: 90
}, {
    type: "foo",
    x: 10,
    y: 50
}, {
    type: "foo",
    x: 220,
    y: 130
}, {
    type: "baz",
    x: 40,
    y: 40
}, {
    type: "bar",
    x: 170,
    y: 20
}, {
    type: "baz",
    x: 220,
    y: 110
}, {
    type: "bar",
    x: 130,
    y: 120
}, {
    type: "foo",
    x: 150,
    y: 50
}, {
    type: "baz",
    x: 30,
    y: 110
}, {
    type: "foo",
    x: 100,
    y: 220
}];

var color = d3.scaleOrdinal()
    .domain(["foo", "bar", "baz"])
    .range(["teal", "brown", "gold"]);

var circles = svg.selectAll(".circles")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", d => d.x)
    .attr("cy", d => d.y)
    .attr("r", 8)
    .attr("fill", d => color(d.type));

circles.on("mouseover", function(d) {
    var filtered = circles.filter(function(e) {
        return e.type != d.type
    });
    filtered.attr("opacity", 0);
}).on("mouseout", function() {
    circles.attr("opacity", 1)
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-16
    • 2016-01-11
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多