据我所知,我不能将addClass或removeClass与SVG一起使用,而且我必须使用attr。但是如何使用jQuery切换SVG的attr。查看我的fiddle。我试图在点击时切换箭头的旋转(参见我的js部分中点击功能的注释部分)。谁有更好的想法如何做到这一点?
我的HTML
<div class="col-md-3 col-sm-4 sidebar">
<div class="title-region">
<a href="">Current Page</a>
<svg class="down-arrow mobile-only" width="17px" height="10px">
<use xlink:href="#down-arrow"></use>
</svg><!--end hamburger-->
</div><!--end title-region-->
<div class="mobile-zipped">
<ul class="sidebar-block children">
<li><a href="">Child One</a></li>
<li><a href="">Child Two</a></li>
<li><a href="">Child Three</a></li>
</ul>
<ul class="sidebar-block siblings">
<li><a href="">Sibling One</a></li>
<li><a href="">Sibling Two</a></li>
<li><a href="">Sibling Three with a super long title</a></li>
<li><a href="">Sibling Four</a></li>
</ul>
</div><!--end mobile-zipped-->
</div><!--end sidebar-->
CSS:
.sidebar {
position: relative;
/*width:270px*/
height: auto;
display: inline-block;
/*margin-right:60px;max-width:25%*/
}
.sidebar .title-region {
position: relative;
height: auto;
background: #005DAA;
width: 100%;
padding: 15px;
}
.sidebar .sidebar-block {
padding: 15px;
}
.sidebar ul {
list-style-type: none;
}
.sidebar .down-arrow {
float: right;
margin-top: 8px;
fill: #00305e;
}
JS包含在小提琴中。非常感谢任何帮助!
答案 0 :(得分:2)
请参阅demo。
var classNames = accordionArrow.attr('class').split(' ');
if ($.inArray("flipped", classNames) != -1) {
//jQuery.grep() to remove duplicates even if multiple occurrences present
classNames = $.grep(classNames, function (element) {
return element !== "flipped";
});
} else {
classNames.push("flipped");
}
accordionArrow.attr('class', classNames.join(' '));
答案 1 :(得分:1)
假设您要在flipped
上添加/删除accordianArrow
课程,您可以使用老式的方式处理课程:
var flipped = /\bflipped\b/;
var cls = accordianArrow.attr("class");
var updated = cls.replace(flipped, '');
if (cls === updated) {
// Didn't have it; add it
cls += " flipped";
} else {
// We removed it, don't leave dangling whitespace (though it doesn't really matter, you could leave this off)
cls = $.trim(cls);
}
accordianArrow.attr("class", cls);