我正在尝试向矩形添加工具提示。它确实会在鼠标指针悬停在栏上时弹出,但它不想在 mouseout 事件中消失。我也尝试过使用 div.style("display", "none"),但它也不起作用。出于某种原因,它不想在鼠标移出后再次触发鼠标悬停事件。它只是不断显示工具提示。
http://bl.ocks.org/edkiljak/dc85bf51a27122380c68909cdd09d388
div.tooltip {
position: absolute;
text-align: left;
padding: 4px;
font-family: Lato, arial, sans-serif;
font-size: 14px;
background: #eee;
border-radius: 2px;
border: 1px solid gray;
pointer-events: none;
}
var div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var bars = barGroup.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", function (d) {
return heightScale(d.Vendor);
})
.attr("width", function (d) {
return widthScale(+d.Share2016)
})
.attr("height", heightScale.bandwidth() / 1.1)
.style("fill", function (d, i) {
return color(i);
})
.on("mouseover",function (d){
div.transition()
.duration(200)
div
.style("opacity", .9)
.html("Vendor: " + "<strong>" + d.Vendor + "</strong>" + "<br>" + "Market share in 2016: " + d.Share2016 + "%")
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
d3.select(this)
.style("fill", "#93ceff")
})
.on("mouseout", function(){
d3.select(this)
.transition()
.duration(50)
.style("fill", function(d,i){
return color(i);
})
d3.select(div).remove()
})
我在这里做错了什么?
最佳答案
问题出在这里:
d3.select(div).remove()
因为 div
本身就是一个选择,所以您选择的是一个选择,这没有什么意义。
取而代之的是,只需在 mouseout
中使用 div
:
div.remove()
或者,更好的是,将其不透明度设置为零:
div.style("opacity", 0)
这里是更新后的 bl.ocks,只有那个变化:http://bl.ocks.org/anonymous/raw/13ce2445b248fb9e44dcd33cfc3dff36/dff0c60423927960cab8aaf9e613c2c3ae205808/
关于javascript - 工具提示不会在鼠标移出时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46060078/