使用鼠标位置更改D3地图工具提示的类别

时间:2014-12-21 16:43:31

标签: javascript html css d3.js

我最近使用D3js和插件d3.tip.js创建an interactive map来编写一个很好的工具提示。我为工具提示的风格编写了这一行:

.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属性使得工具提示显示在鼠标光标下:The tooltip

工具提示适用于我的大多数区域,但iframe的右上角存在问题,如下所示:

The tooltip issue

所以我想知道我是否可以通过在iframe中测试鼠标的x位置来应用具有不同margin-left值的其他类。

如果x位置在我的限制之后,工具提示在光标左侧会更多,否则它会向右移动。

你认为这可能吗?我搜索时没有发现任何我能适应的东西。这是a link to fork all the code in gitHub

提前致谢!

1 个答案:

答案 0 :(得分:3)

您可以在事件处理函数中修改tip元素上的类。您可以创建自己的事件处理程序来计算是否需要重新定位提示,相应地设置类,并使用正确的参数调用tip.show,而不是将tip.show()直接传递给mouseover事件。

需要注意的事项:

  • d3.tip未实现classed()方法来切换单个类,因此您必须重置整个类属性。

  • tip.show()会重置默认类本身,因此您需要在显示提示后设置自定义类

  • 如果要将d,i变量用于html更新功能,则需要将tip.show()变量传递给/* 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>
{{1}}