如何实现手风琴点击切换Font Awesome图标且将图标置于文本后方
核心修改逻辑
现有代码图标展示在文字前方的原因是JS逻辑中先插入图标元素,再追加文本,调整两者插入顺序即可实现图标后置,同时调整判断逻辑匹配所需的切换规则。
适配「始终显示Categories仅切换图标」需求的代码
修改后的JS如下:
function arata_ascunde(h1) { var x = $('#showhide'); $(h1).find('i').remove(); if ($(h1).text().trim() == 'Categories') { // 先写入文本,再追加图标,实现图标在文字后方 $(h1).text('Categories ').append($('<i/>',{class:'fa fa-chevron-up'})); x.fadeIn(); } else { $(h1).text('Categories ').append($('<i/>',{class:'fa fa-chevron-down'})); x.fadeOut(); } }
同步调整HTML的初始结构,保证默认状态图标就在文字后方:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <h1 onclick="arata_ascunde(this);" class="btn btn-info " id="show_hide_bt"> Categories <i class="fa fa-chevron-down"></i> </h1> <div id="showhide" style="display:none;"> <ul> <li><a href="#">Hello World</a></li> </ul> </div>
若需要保留「展开时显示Hide」的交互逻辑,使用以下JS即可
function arata_ascunde(h1) { var x = $('#showhide'); $(h1).find('i').remove(); if ($(h1).text().trim() == 'Categories') { $(h1).text('Hide ').append($('<i/>',{class:'fa fa-chevron-up'})); x.fadeIn(); } else { $(h1).text('Categories ').append($('<i/>',{class:'fa fa-chevron-down'})); x.fadeOut(); } }
内容的提问来源于stack exchange,提问作者Chad。
相关产品推荐
相关产品推荐

