我一直在使用带有内置工具提示的 D3 svg 图表(我相信使用 d3-tip 库)。原始代码可以在这里看到:http://bl.ocks.org/Caged/6476579
我已经成功地能够自定义它的大部分内容,但我需要添加第二个鼠标悬停效果;这样,当您将鼠标悬停在某个栏上时,它不仅会打开工具提示,还会打开图表右上角的另一个提示或图层。
我尝试执行以下操作,但似乎不起作用。我只是在语法中遗漏了一些东西吗?或者这个策略根本不起作用?
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<strong>Frequency2:</strong> <span style='color:red'>" + d.frequency2 + "</span>";
})
//adding second tool tip
var tip2 = d3.tip()
.attr('class', 'd3-tip')
.offset([-40, 0])
.html(function(d) {
return "<strong>Other Variables:</strong> <span style='color:red'>" + d.frequency2 + "</span>";
})
然后
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency2); })
.attr("height", function(d) { return height - y(d.frequency2); })
.on('mouseover', tip.show, tip2.show)
.on('mouseout', tip.hide, tip2.hide);
图表仍然有效,但现在两个工具提示均不显示。
最佳答案
你现在在做什么...
.on('mouseover', tip.show, tip2.show)
...不会工作。在 selection.on
中,第三个参数是 capture :
selection.on(typenames[, listener[, capture]])
因此,解决方案是将 tip
和 tip2
包装在另一个函数中:
.on("mouseover", function() {
tip.show();
tip2.show();
})
这是一个演示(将鼠标悬停在圆圈上):
var svg = d3.select("svg");
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 20])
.html("<strong>Frequency2:</strong> <span style='color:red'>foo</span>")
var tip2 = d3.tip()
.attr('class', 'd3-tip')
.offset([90, 20])
.html("<strong>Other Variables:</strong> <span style='color:red'>bar</span>")
svg.call(tip)
svg.call(tip2)
d3.select("circle").on("mouseover", function() {
tip.show();
tip2.show();
}).on("mouseout", function() {
tip.hide();
tip2.hide();
});
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>
<svg>
<circle cx="50" cy="70" r="20" fill="teal"></circle>
</svg>
关于javascript - 如何向条形图添加多个工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42914972/