简体   繁体   English

svg rect元素上的classList无法正常工作

[英]classList on svg rect element not working as I would expect

I'm messing up with SVG and I can't figure out why I can't toggle class on rect element. 我搞砸了SVG,我不明白为什么我不能在rect元素上切换类。 Tested only in Chrome and it does not work correctly. 仅在Chrome中进行了测试,但无法正常运行。 Here is the JSFiddle : 这是JSFiddle

HTML 的HTML

<svg>
    <rect x="10" y="10" width="48" height="6"></rect>
</svg>

CSS 的CSS

body {
    margin: 0;
}
svg {
    cursor: pointer;
}
.rotate {
    transform: rotate(45deg);
}

JS JS

var svg = document.querySelector('svg');
svg.onclick = function () {
    this.firstElementChild.classList.toggle('rotate');
};

So, you need to add the base statement of the rotate to the element else when you remove the class it still has the property of the rotate due to the way transform in svgs works in Chrome . 所以,你需要的的基础语句添加rotate到别的元素,当你删除它仍然具有途中由于该旋转的属性的类在Chrome svgs工程改造。

As noticed by @RobertLongson this is only a workaround for chrome because it works fine in other browsers. 正如@RobertLongson所注意到的,这只是chrome的一种解决方法,因为它在其他浏览器中可以正常工作。

 var svg = document.querySelector('svg'); svg.onclick = function () { this.firstElementChild.classList.toggle('rotate'); }; 
 body { margin: 0; } svg { cursor: pointer; } svg rect { transform: rotate(0deg); } .rotate { transform: rotate(45deg); } 
 <svg> <rect x="10" y="10" width="48" height="6"></rect> </svg> 

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

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