D3 在鼠标悬停事件后重新分配元素属性

问题描述 投票:0回答:1

我有一个带有

mouseenter, mouseleave
事件的多线图表,一次突出显示一行,并在鼠标离开时使其变暗

此图表中还有一些按钮,用户可以选择查看单线: enter image description here

单击按钮时,不透明度会设置回“1”以禁用鼠标事件效果。但这不起作用,结果是由于之前的鼠标事件影响,所选行变暗了。

像这样: enter image description here

以下是我的代码:

lineGraph
    .on("mouseenter",
        function(event) {
            const thisPath = d3.select(this);
            thisPath.style("opacity", 1);
            thisPath.attr("stroke-width", 2.25);
            thisPath.raise();
        }
        )
    .on("mouseleave",
        function(event){
            const thisPath = d3.select(this);
            thisPath.style("opacity", 0.25);
        }
    );

// ---------------------------------------------------------- ---

// 按钮更改时,更新样式

// ---------------------------------------------------------- ---

d3.selectAll(".button")
    .on('click', function(event) {
        const selectedMethod = event.target.innerHTML;
        var selectedLine = d3.select("#" +selectedMethod);
        methodSelection.forEach((method, index) => {
        if (index < 1) return;
        if (selectedMethod == "All") {
            selectedLine = d3.selectAll("#" + method);
            selectedLine.attr("opacity",1);
        }
        else {
            if (method == selectedMethod) {
                selectedLine = d3.selectAll("#" +selectedMethod);
                selectedLine.attr("opacity",1);
            }
            else {
                var unselectdLine = d3.selectAll("#" + method);
                unselectdLine.attr("display", "none");
            }
        }
        })
        });

我无法弄清楚为什么设置

opacity = 1
在这种情况下不起作用。

任何帮助将不胜感激!

javascript d3.js
1个回答
0
投票

风格优先于属性。您正在设置鼠标事件的样式,并尝试使用按钮单击的属性覆盖该样式。

您可以通过将

selectedLine.attr("opacity",1)
替换为
selectedLine.style("opacity",1)
来修复它。

© www.soinside.com 2019 - 2024. All rights reserved.