简体   繁体   English

使用JS和SVG动态添加和删除类时遇到麻烦

[英]Having trouble dynamically adding and removing classes with JS and SVG's

I'm trying to create an interaction where every-time you click on an icon, a green border appears below it, and the green border that was on the last icon clicked gets removed. 我正在尝试创建一个交互,每次您单击一个图标时,该图标下方都会出现一个绿色边框,而最后单击的图标上的绿色边框将被删除。 But when the page loads, the green border, by default, will be under the first icon. 但是,当页面加载时,默认情况下,绿色边框将位于第一个图标下方。 I wanted it that way. 我想要那样。

I tried to achieve this effect by adding and removing the class "side-effect" to the li elements under the ul-side parent container. 我试图通过在ul-side父容器下的li元素中添加和删除类“副作用”来实现此效果。 For some reason my code isn't running at all. 由于某种原因,我的代码根本没有运行。

Here is the Javascript I wrote. 这是我写的Javascript。 Other relevant code can be found in the fiddle link below. 其他相关代码可以在下面的小提琴链接中找到。 const sideNavList=document.getElementsByClassName("ul-side")[0]; const sideNavList = document.getElementsByClassName(“ ul-side”)[0]; const navigationChildren=sideNavList.children; const navigationChildren = sideNavList.children;

sideNavList.addEventListener('click', function(e){
    if (e.target.classList.contains("side-item")) {
        liNavTarget=e.target;
        for (let i=0; i<navigationChildren.length; i+=1) {
            if (navigationChildren[i].classList.contains("side-effect")) {
                navigationChildren[i].classList.remove("side-effect");
                liNavTarget.classList.add("side-effect");
            }
        }
    }
});

https://jsfiddle.net/apasric4/mg2Lu0no/4/ https://jsfiddle.net/apasric4/mg2Lu0no/4/

Could anyone help me correct my code? 有人可以帮助我更正我的代码吗?

You should learn to use console.log() -- call it like console.log(e.target) at the top of your function and you'd see that your click events are registering on the SVG elements, not the <li> s. 您应该学习使用console.log() -在函数顶部像console.log(e.target)一样调用它,您会发现单击事件正在SVG元素上注册,而不是在<li> s。 There are several workarounds for this, one of which is to prevent pointer-events on the SVG and anchor elements: 有几种解决方法,其中一种是防止SVG和anchor元素上发生指针事件:

https://jsfiddle.net/1zt0vxm4/ https://jsfiddle.net/1zt0vxm4/

.side-anchor {
  pointer-events: none;
}

.side-svg {
  pointer-events: none;
}

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

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