我正在尝试用Jquery制作手风琴,我只希望打开的选择具有活动图标,但此时我的功能将其应用于所有选择。
有人能看出问题所在吗?
小提琴:
https://jsfiddle.net/jcuuc3e7/
代码:
<div id="accordion">
<div class="accordion-segment">
<a class="accordion-open" href="#samarbejdspartnere">
<h3>Samarbejdspartnere</h3>
<svg class="accordion-icon" width="13" height="8">
<path d="M13.6,1.6L12,0L6.8,5.2L1.6,0L0,1.6l6.8,6.8L13.6,1.6z M13.6,1.6"/>
</svg>
</a>
<div>
<ul class="accordion-content">
<li>
<a href="#">Stuff</a>
</li>
<li>
<a href="#">Stuff</a>
</li>
<li>
<a href="#">Stuff</a>
</li>
</ul>
</div>
</div>
<div class="accordion-segment">
<a class="accordion-open" href="#nyheder">
<h3>Nyheder</h3>
<svg class="accordion-icon" width="13" height="8">
<path d="M13.6,1.6L12,0L6.8,5.2L1.6,0L0,1.6l6.8,6.8L13.6,1.6z M13.6,1.6"/>
</svg>
</a>
<div class="accordion-content">
<ul>
<li>
<a href="#">Nyhed 1</a>
</li>
<li>
<a href="#">Nyhed 2</a>
</li>
<li>
<a href="#">Nyhed 3</a>
</li>
<li>
<a href="#">Nyhed 4</a>
</li>
</ul>
</div>
</div>
</div>
$(function() {
$("#accordion").accordion({
collapsible: true,
active: false,
heightStyle: "content",
animate: 250,
header: "a"
});
});
$(".accordion-open").click(function() {
var accIcon = $(".accordion-icon");
accIcon.each(function() {
$(this).removeClass("accordion-icon-active");
});
if (!$(this).hasClass("ui-state-active")) {
accIcon.addClass("accordion-icon-active");
}
});
.accordion-segment {
width: 400px;
border-bottom: 1px solid $oslo-gray;
}
.accordion-open {
display: flex;
width: 100%;
height: 45px;
align-items: center;
text-align: left;
font-size: 18px;
text-transform: uppercase;
}
.accordion-icon {
width: 13px;
height: 8px;
margin-left: auto;
fill: red;
transition: .25s ease;
}
.accordion-icon-active {
transform: rotate(90deg);
transition: .25s ease;
}
.accordion-content {
margin-top: 10px;
padding-bottom: 30px;
text-align: left;
font-size: 14px;
line-height: 1.5;
}
答案 0 :(得分:2)
通过此accIcon.addClass("accordion-icon-active");
,您将accordion-icon-active
类添加到所有.accordion-icon
项中。但是你想把这个类添加到被点击的项目中,所以你应该:
if (!$(this).hasClass("ui-state-active")) {
$(this).find('.accordion-icon').addClass("accordion-icon-active");
}
另请注意此代码:
accIcon.each(function() {
$(this).removeClass("accordion-icon-active");
});
与:
相同accIcon.removeClass("accordion-icon-active");
这里不需要迭代,jquery会处理它。
答案 1 :(得分:0)
您正在手风琴 - 开放式点击处理程序
中设置页面上每个图标的状态我认为它应该是更像这样的东西
$(".accordion-open").click(function() {
$('.accordion-icon').each(function(i, elem) {
console.log(elem);
$(elem).removeClass("accordion-icon-active");
});
if ($(this).hasClass("ui-state-active")) {
var accIcon = $(this).find(".accordion-icon");
accIcon.addClass("accordion-icon-active");
}
});
现在点击每个手风琴图标只会设置一个图标的状态。