我最近使用D3js和插件d3.tip.js制作了一个交互式地图,以编写一个不错的工具提示。我为工具提示的样式写了以下这些行:
.d3-tip {
line-height: 1.5;
font-weight: normal;
font-family: Arial;
padding: 5px;
background: rgba(125, 125, 125, 0.9);
color: white;
border-radius: 4px;
font-size: 11px!important;
margin-left: 25px;
margin-top: 205px;
}
margin-left和margin-top属性使工具提示显示在鼠标光标下方,如下所示:
工具提示在我的大部分地区都可以正常使用,但是iframe的右上角存在问题,如下所示:
因此,我想知道是否可以通过测试iframe中鼠标的x位置来应用具有不同的margin-left值的其他类。
如果x位置在我的限制之后,则工具提示会在光标的左侧更多,否则会在右侧更多。
Do you think these is it possible ? I searched without finding anything which I could adapt. Here's a link to fork all the code in gitHub.
Thanks in advance !
You can modify the classes on the tip element in your event handler function. Instead of passing tip.show
directly to the mouseover event, you can create your own event handler that calculates whether the tip needs to be re-positioned, sets the classes accordingly, and also calls tip.show()
with the correct parameters.
Things to be aware of:
d3.tip
doesn't implement the classed()
method to toggle individual classes, so you have to reset the entire class attribute.
tip.show()
resets the default classes itself, so you need to set your custom classes after you show the tip.
您需要将d,i
变量传递给tip.show()
html更新功能中要使用的变量。
下面是一个简化的示例。提示默认显示在矩形的顶部边缘,我检查是否将提示推离页面的顶部边缘,并设置一个类来翻译提示(如果这样)。
/* Initialize tooltip */
tip = d3.tip()
.html(function(d, i) { return "Rectangle #" + i; });
/* Invoke the tip in the context of your visualization */
vis = d3.select("svg")
vis.call(tip)
vis.selectAll('rect')
.datum(function(d){
//save the old data (null in this example)
//as a sub-property of a new data object
//which also contains position information
return {data:d, position:(this.x, this.y)};
})
.on('mouseover', function(d, i){
//save the moused-over graphical element in a variable
var rect = this;
tip.show(d, i); //show the tip (will call the .html function)
tip.attr('class', function(){
//use the properties of the moused-over element
//to modify the classes on the tip object:
if (rect.getBBox().y < 50)
return 'd3-tip n down'
else
return 'd3-tip n';
})
})
.on('mouseout', tip.hide)
rect {
fill: yellow;
stroke: blue;
}
.d3-tip {
background: white;
border: solid gray;
border-radius: 0.5em;
padding: 0.25em;
}
.d3-tip.down {
-webkit-transform: translate(0, 2em);
transform: translate(0, 2em);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.6.3/d3-tip.min.js"></script>
<svg width="400px" height="400px">
<rect x="0" y="0" width="100" height="100" />
<rect x="100" y="0" width="100" height="100" />
<rect x="0" y="100" width="100" height="100" />
<rect x="100" y="100" width="100" height="100" />
</svg>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句