D3-将鼠标悬停在x位置 [英] D3 - get x position on mouseover

查看:77
本文介绍了D3-将鼠标悬停在x位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有个笨蛋- https://plnkr.co/edit/iOGJUosvruW9KV1FF9lp?p =预览

在鼠标悬停在栏上时,我想显示一个工具提示

On mouseover of the bars I want to show a tooltip

此刻,它随鼠标移动,但我希望它位于我所经过的小节上方的固定位置.

At the moment it move with the mouse but I want it to be a set position above the bars I'm over.

如何获取我结束的栏的x和y位置

How do I get the x and y position of the bar I'm over

我已经尝试过,但是出现错误.

I have tried, but I get errors.

console.log(d3.mouse(this)[0]); 

推荐答案

在MDN中解释:

箭头函数表达式的语法比函数短 表达式和没有它自己的,参数,super或 新目标.这些函数表达式最适合非方法 函数,它们不能用作构造函数.

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

箭头函数被引入为纯函数,这就是为什么它们不这样做的原因具有这种上下文变量.

Arrow functions are introduced to be pure functions, and that's the reason why they don't have this kind of context variables.

只需将箭头功能转换为常规功能即可.我为你的朋克分叉了:

Just convert the arrow function to a regular one. I forked your plunker:

https://plnkr.co/edit/3Y4T0JZ42eH2wb42tpsg?p=preview

d3.selectAll('.bar').on("mouseover", function(){
   console.log(d3.mouse(this)[0]);
   d3.select('.chart-tooltip').style("display", null)
})

更新:

您也可以将其替换为全局d3.event.target并将该功能保留为箭头功能.

You can also replace this with the global d3.event.target and keep the function as an arrow function.

d3.selectAll('.bar').on("mouseover", () => {
  console.log(d3.mouse(d3.event.target)[0]);
  d3.select('.chart-tooltip').style("display", null)
})

更新II:

Gerardo Furtado建议使用回调的第三个参数来获取html元素.这也是一个很好的解决方案,因为d3.event在某些情况下可能会出现问题.

Gerardo Furtado proposed to use the third argument of the callback to get the html element. Also a good solution, as d3.event can be problematic in certain situations.

d3.selectAll('.bar').on("mouseover", (datum,index,elements) => {
  console.log(d3.mouse(elements[index])[0]);
  d3.select('.chart-tooltip').style("display", null)
})

这篇关于D3-将鼠标悬停在x位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆