【问题标题】:D3 - get x position on mouseover [duplicate]D3-鼠标悬停时获取x位置[重复]
【发布时间】:2019-04-11 19:06:27
【问题描述】:

我这里有一个笨蛋 - https://plnkr.co/edit/iOGJUosvruW9KV1FF9lp?p=preview

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

目前它随鼠标移动,但我希望它位于我结束的栏上方的设定位置。

我如何获得我所在栏的 x 和 y 位置

我试过了,但我得到了错误。

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

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    作为explained in MDN:

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

    箭头函数被引入为pure functions,这就是它们没有这种上下文变量的原因。

    只需将箭头函数转换为常规函数即可。我叉了你的 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 并将函数保留为箭头函数。

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

    更新二:

    Gerardo Furtado proposed to use the third argument 获取html元素的回调。这也是一个很好的解决方案,因为d3.event 在某些情况下可能会出现问题。

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

    【讨论】:

    • +1,但d3.event.target 不是箭头函数的好选择,请在此处查看我的答案:stackoverflow.com/a/42667743/5768908。只需使用第三个和第二个参数。
    • @GerardoFurtado 已更新!
    猜你喜欢
    • 2015-04-22
    • 2013-04-07
    • 2015-10-18
    • 1970-01-01
    • 2015-02-20
    • 2016-03-14
    • 2011-09-27
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多