目标一个特定的数据目标按钮时,使用几个引导折叠元素?



我在我的网站上使用了几个Bootstrap折叠元素。折叠元素由read-more按钮控制,这些按钮中有一个图标,该图标根据折叠元素的状态而变化。我通过向按钮添加一个类来实现这一点。问题是类被添加到所有按钮中。如何将类仅添加到特定的折叠元素按钮?

代码如下:

<div class="collapse extra-text" id="collapse1">
<p class="">Hidden text</p>

</div>
<p>
<a class="read-more" data-bs-toggle="collapse" data-bs-target="#collapse1" aria-expanded="false" aria-controls="collapseExample">Read more </a>
</p>

js:

<script>
$('.extra-text').on('hidden.bs.collapse', function () {
$('.read-more').removeClass('active');

});
$('.extra-text').on('shown.bs.collapse', function () {
$('.read-more').addClass('active');
});
</script>

和css:

a.read-more:after {
font-family: "Font Awesome 5 Free";
content: "f078";
display: inline-block;
transition: all 0.5s;
}

a.read-more.active:after {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
transform: rotate(180deg);
}

您可以使用.prev().find()方法从折叠div中访问前一个元素,然后在那里添加/删除类。

演示代码 :

$('.extra-text').on('hidden.bs.collapse', function(e) {
//get prev elements > p tag and then use .find to get readmore tag
$(this).prev().find('a.read-more').removeClass('active');
});
$('.extra-text').on('shown.bs.collapse', function(e) {
$(this).prev().find('a.read-more').addClass('active');
});
a.read-more::after {
font-family: "Font Awesome 5 Free";
content: "f078";
display: inline-block;
transition: all 0.5s;
font-weight: 900;
}
a.read-more.active:after {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
transform: rotate(180deg);
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
<p>
<a class="read-more" data-bs-toggle="collapse" data-bs-target="#collapse1" aria-expanded="false" aria-controls="collapseExample">Read more </a>
</p>
<div class="collapse extra-text" id="collapse1">
<p class="">Hidden text</p>
</div>
<p>
<a class="read-more" data-bs-toggle="collapse" data-bs-target="#collapse2" aria-expanded="false" aria-controls="collapseExample">Read more </a>
</p>
<div class="collapse extra-text" id="collapse2">
<p class="">Hidden text</p>
</div>

相关内容

  • 没有找到相关文章

最新更新