本组件基于weui.css 及 jQuery。
一、CSS部分,主要是动画效果
@import url('https://weui.io/style/weui.css');
/* accordion */
.accordion>*{
background-color: var(--weui-BG-2);
}
.accordion-button{
padding: 16px;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-transition: .3s;
-o-transition: .3s;
transition: .3s;
cursor: pointer;
margin-top :8px;
}
.accordion-button+*{
display:none;
}
.accordion-button:not(.collapsed){
opacity: .5;
}
.accordion-button:not(.collapsed)::after {
-webkit-transform: rotate(-180deg);
-ms-transform: rotate(-180deg);
transform: rotate(-180deg);
}
.accordion-button::after {
--button-icon:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='hsla(0%2C0%25%2C100%25%2C.8)'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
content: "";
width: 1.25rem;
height: 1.25rem;
-webkit-mask-position: 0 0;
mask-position: 0 0;
-webkit-mask-repeat: no-repeat;
mask-repeat: no-repeat;
-webkit-mask-size: 100%;
mask-size: 100%;
background-color: currentColor;
color: var(--weui-FG-0);
-webkit-mask-image: var(--button-icon);
mask-image: var(--button-icon);
-webkit-transition: -webkit-transform 0.2s ease-in-out;
transition: -webkit-transform 0.2s ease-in-out;
-o-transition: transform 0.2s ease-in-out;
transition: transform 0.2s ease-in-out;
transition: transform 0.2s ease-in-out, -webkit-transform 0.2s ease-in-out;
}
二、html部分
<!--方案一-->
<ul class="accordion">
<li>
<div class="weui-flex accordion-button collapsed">
<p class="weui-flex__item">项目一</p>
</div>
<section>
项目一内容...
</section>
</li>
<li>
<div class="weui-flex accordion-button collapsed">
<p class="weui-flex__item">项目二</p>
</div>
<section>
项目二内容...
</section>
</li>
<li>
<div class="weui-flex accordion-button collapsed">
<p class="weui-flex__item">项目三</p>
</div>
<section>
项目三内容...
</section>
</li>
</ul>
<!--方案二-->
<dl class="accordion">
<dt class="weui-flex accordion-button collapsed">
<p class="weui-flex__item">项目一</p>
</dt>
<dd>
项目一内容...
</dd>
<dt class="weui-flex accordion-button collapsed">
<p class="weui-flex__item">项目二</p>
</dt>
<dd>
项目二内容...
</dd>
<dt class="weui-flex accordion-button collapsed">
<p class="weui-flex__item">项目三</p>
</dt>
<dd>
项目三内容...
</dd>
</dl>
三、JS部分
// 依赖Jquery
// 适合一个页面多次使用该组件,去掉.collapsed 的项,表示默认展开
$(function(){
$('.accordion').each(function(){
var $btns = $(this).find('.accordion-button');
$btns
.on('click',function(event){
var $btn = $(this);
var isHide = $btn.is('.collapsed'); // 获取该按钮的初始状态
$btns.addClass('collapsed').next().slideUp(); // 设置所有项为隐藏状态
isHide && $btn.removeClass('collapsed').next().slideDown(); // 如果初始为隐藏的按钮,则移除按钮隐藏样式并展开显示
event.stopPropagation();
})
.not('.collapsed')
.next()
.show();
});
});