简体   繁体   English

d3鼠标悬停一次绘制

[英]d3 draw once on mouseover

Im using using d3js to create a list of buttons - which i am able to do successfully. 我正在使用d3js创建按钮列表-我能够成功做到这一点。

I am trying to add an X (close) button when you hover over the button. 当您将鼠标悬停在按钮上时,我试图添加一个X(关闭)按钮。 The x appears, however, inspecting the DOM, the x element is drawn endless amounts of times. x出现了,但是,检查DOM,x元素被绘制了无数次。

btnArray.forEach(function (button) {

    const btn = document.createElement('div');
    btn.type = 'button';
    btn.value = button.name;
    btn.onClick = evt => {
        // do soemthing on click
    }

    btn.onmouseover = function(e) {
        var me = d3.select(btn);
        me.append('div')
            .classed({'btn-close': true})
            .text('x');
    }

    btn.onmouseout = function(e) {
        var me = d3.select(btn);
        me.selectAll('btn-close')
            .remove();
    }

});

The reason that you're seeing the "X" endless times is because the element is being appended at every mouseover but it is not being removed. 您看到"X"无休止时间的原因是因为该元素在每次鼠标悬停时都会附加,但不会被删除。 This is why: 这就是为什么:

You are setting a class... 您正在设定课程...

.classed({'btn-close': true})

But you're not selecting by class: 但您不是按班级选择:

me.selectAll('btn-close')

It should be: 它应该是:

me.selectAll('.btn-close')
//class here--^

PS: This is out of the scope of your question, but I'd like to make some considerations about your code. PS:这超出了您的问题范围,但是我想对您的代码进行一些考虑。 Please take this as a constructive criticism, so you can write a more idiomatic D3: 请将此作为建设性的批评,以便您可以编写更惯用的D3:

  1. You don't need loops for appending elements in a D3 code. 您不需要循环即可在D3代码中附加元素。 Use selections . 使用选择 An idiomatic D3 code has very few loops, if any. 惯用的D3代码几乎没有循环。
  2. Use D3 methods for manipulating the DOM. 使用D3方法来操作DOM。 There is no problem with document.createElement('div') (by the way, you're missing the appendChild ), but you could do that using D3 methods. document.createElement('div')没问题document.createElement('div')顺便说一句,您缺少了appendChild ),但是您可以使用D3方法来实现。
  3. Instead of removing and appending the same element, you could change its opacity, or the display. 除了删除和附加相同的元素外,您还可以更改其不透明度或显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM