jquery toggleClass的孩子悬停



我试图在悬停元素中切换子类。但是我做错了什么…Can 't figure out what

假设在html:

中有这个svg
<svg id="toplogo" height="200" width="200" alt="" viewBox="0 0 492.69 617.696">
<circle class="fill" fill="#00bbff" stroke="#000000" stroke-width="32" stroke-miterlimit="10" cx="246.16" cy="222.62" r="206.843"/>
</svg>

和这个jquery (inside document ready):

$("#toplogo").hover(function() {
$(this).children('.fill').toggleClass('hoverfill');
});

这个css:

.hoverfill {
    fill: #ff0000;
}

什么也不会发生。未更改填充

看到它在http://jsfiddle.net/k4djq/1/

但是当我用

进行测试时,它可以工作
$("#toplogo").hover(function() {
$(this).children('.defaultstroke').css("fill","#ff0000");
});

更新

最好使用css来获得悬停/取消悬停效果

演示工作

#toplogo:hover circle {
    fill: #ff0000;
}

尝试.attr(), .add/toggleClass()不与SVG一起工作,

$("#toplogo").hover(function() {
    $(this).children('.fill').attr('class','hoverfill');
});

circle也有属性填充,所以你可以使用:

$(this).children('.fill').attr('fill','#ff0000');

参考

:

jQuery设计用于处理HTML DOM(和XML DOM)。然而SVG DOM略有不同,并不是所有的jQuery函数都能工作正确。

有一些插件可以让它工作:

http://keith-wood.name/svg.html dom

根据我的经验,每次使用脚本来编辑元素的样式时,最好总是尝试直接从源代码进行编辑。

试试这个:

完全删除该函数,只需添加以下CSS选择器

#toplogo:hover .fill { fill: #ff0000; }

我认为你必须使用attr而不是class,因为颜色来自于attr fill

js

$("#toplogo").on("mouseenter mouseleave", 
             function(e){
                 var color = $("#orgColor").attr("color");
                 if(e.type == "mouseenter"){
                     $(this).children('.fill').attr("fill", "blue");
                 }
                 else if(e.type == "mouseleave"){
                     $(this).children('.fill').attr("fill", color);
                 }

});

小提琴

我还在你的html中添加了一个隐藏的输入来保持原来的颜色。检查小提琴

最新更新