我正在使用面向对象的javascript进行accordian
这里的问题是当我点击时切换功能无效。正如我所期望的那样,当我点击显示内容时,输出将是{{1}和其他孩子close.initially,firstchild将是+
。
我刚开始学习面向对象的javascript.Anything错误的代码让我知道。
active
Accordion = {
accordionContent: '.accordion-s1 .accordion--content p',
accordionTitle: '.accordion--title',
init: function() {
$(this.accordionTitle).click(this.toggleAccordion.bind(this));
},
toggleAccordion: function() {
$(this.accordionContent).slideToggle();
$(this.accordionTitle).removeClass("active");
if($(this.accordionTitle).siblings().is(":visible")) {
$(this.accordionTitle).siblings().slideDown();
$(this).find('.fa.fa-times').toggleClass('plus');
$(this.accordionTitle).addClass("active");
}
}
}
$(document).ready(function(){
Accordian.init();
});
.accordion-s1 .accordion--title {
display: flex;
flex-direction: row;
padding: 10px;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
font-weight: 300;
transition: all .25s ease;
background-color: #2783e8;
color: #ffffff;
}
.accordion-s1 .accordion--title h4 { flex:1;font-weight: 600;}
.accordion-s1 .aticon-times { padding: 5px;}
.plus {
transform: rotate(45deg);
transition: all .25s ease;
}
.accordion-s1 .accordion--content {
padding: 10px 20px;
background: whitesmoke;
}
答案 0 :(得分:2)
我从你给定的代码中发现了一些错误。 $(this.accordionContent).slideToggle()
实际上定位了所有元素。同样是$(this.accordionTitle).siblings()
。
您好,您可以尝试以下代码:
Accordion = {
accordionContent: '.accordion-s1 .accordion--content',
accordionTitle: '.accordion--title',
init: function() {
$(this.accordionTitle).removeClass('active').eq(0).addClass("active");
$(this.accordionContent).slideUp().eq(0).slideDown();
$(this.accordionTitle).click(this.toggleAccordion.bind(this));
},
toggleAccordion: function(e) {
if($(e.currentTarget).next($(this.accordionContent)).is(":visible")) {
return
}
$(this.accordionTitle).siblings().slideUp();
$(this.accordionTitle).removeClass('active');
$(e.currentTarget).next($(this.accordionContent)).slideDown();
$(e.currentTarget).addClass("active");
}
}
$(document).ready(function(){
Accordion.init();
});
对于加号,您还需要调整CSS和HTML标题部分。
在CSS中:
.accordion--i .fa-times {
display:inline-block;
}
.accordion--i .fa-plus {
display:none;
}
.active .accordion--i .fa-times {
display:none;
}
.active .accordion--i .fa-plus {
display:inline-block;
}
在HTML中,您需要在每个块中的每个标题中添加以下更改:
<div class="accordion--title">
<h4>London Style</h4>
<span class="accordion--i">
<i class="fa fa-times aticon-times"></i>
<i class="fa fa-plus aticon-times"></i>
</span>
</div>