单击时Jquery向下滑动切换更改按钮文本和图标
Posted
技术标签:
【中文标题】单击时Jquery向下滑动切换更改按钮文本和图标【英文标题】:Jquery slidedown toggle change button text and icon when clicked 【发布时间】:2022-01-07 15:56:44 【问题描述】:向下滑动功能很好,但是当单击按钮时,我需要将按钮中的文本和字体真棒图标从“打开所有问题(向下图标)”更改为“关闭所有问题(向上图标)”,然后在关闭时恢复为“打开所有问题”。谢谢! [
$(document).ready(function()
$("#showNavBut").click(function()
$("#showNav").slideToggle();
if ( $('#showNav').css('display').display == 'block' )
$('#showNavBut').html('Close all questions <i class="fas fa-chevron-up" aria-hidden="true"></i>'); // Change button text
else
$('#showNavBut').html('Open all questions <i class="fas fa-chevron-down" aria-hidden="true"></i>'); // Change button text
);
);
#showNav display: none;
<link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="showNav">
<div class="#">
<a href="#">Confidence Household 1</a>
<a href="#">Confidence Household 2</a>
<a href="#">Confidence Household 3</a>
<a href="#">Confidence-Household 3</a>
</div>
</div>
<button id="showNavBut" class="show-nav-but" style="width: auto;">Open all questions <i class="fas fa-chevron-down" aria-hidden="true"></i></button>
</div>
]1
【问题讨论】:
【参考方案1】:看起来问题是你没有等待 showNav 采取阻止/无状态,在按下按钮的那一刻它有一个状态,但需要一些时间执行slideToggle,执行slideToggle
后只需要使用回调函数改变按钮的状态即可$(document).ready(function ()
$("#showNavBut").click(function (event)
$("#showNav").slideToggle(500, function ()
if ($('#showNav').is(':visible'))
$(event.currentTarget).html('Close all questions <i class="fas fa-chevron-up" aria-hidden="true"></i>');
else
$(event.currentTarget).html('Open all questions <i class="fas fa-chevron-down" aria-hidden="true"></i>');
);
);
);
#showNav
display: none;
<link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="showNav">
<div class="#">
<a href="#">Confidence Household 1</a>
<a href="#">Confidence Household 2</a>
<a href="#">Confidence Household 3</a>
<a href="#">Confidence-Household 3</a>
</div>
</div>
<button id="showNavBut" class="show-nav-but" style="width: auto;">Open all questions <i class="fas fa-chevron-down" aria-hidden="true"></i></button>
【讨论】:
以上是关于单击时Jquery向下滑动切换更改按钮文本和图标的主要内容,如果未能解决你的问题,请参考以下文章