[英]How to change prepended text when toggled in Jquery?
我有一些使用Jquery切换功能显示/隐藏的内容。
我已在每个标题前添加了一个箭头,并希望在切换内容时将其更改为向下箭头。
到目前为止的代码:
$(document).ready(function(){
$('.show-hide-list h3 a').prepend('> ');//Prepend arrow
$('.show-hide-list li .show-hide-list-content').hide();//Hide content
$('.show-hide-list h3').click(function() {//Perform toggle when clicked
$(this).next('.show-hide-list-content').toggle();
//Need to change orientation of prepended arrow when toggled
return false;
});
});
html如下:
<ul class="show-hide-list">
<li>
<h3><a href="#">Heading</a></h3>
<div class="show-hide-list-content">
Content to be toggled here.
</div>
</li>
</ul>
切换后如何更改箭头方向?
将您的箭头包裹在一个span标签中,以便您轻松选择它。
$(document).ready(function(){
$('.show-hide-list h3 a').prepend('<span>> </span>');//Prepend arrow
$('.show-hide-list li .show-hide-list-content').hide();//Hide content
$('.show-hide-list h3').click(function() {//Perform toggle when clicked
$(this).next('.show-hide-list-content').toggle();
var arrow = $(this).find('span');
if (arrow.text().indexOf('V') >= 0) {
arrow.html('> ');
} else {
arrow.html('V ');
}
//Need to change orientation of prepended arrow when toggled
return false;
});
});
您可以将一个类应用于该箭头,前提是您的用户的浏览器将支持该箭头。 从这样的一些CSS开始:
-webkit-transform: rotate(-270deg);
-moz-transform: rotate(-270deg);
或者,只需切换向下箭头图像的可见性,即可在任何现代浏览器上使用。
只需将箭头放在<span>
并为其指定适当的类,以便稍后可以再次找到它:例如,如下所示:
$(document).ready(function(){
$('.show-hide-list h3 a').prepend('<span class="togglearrow">> </span>');
//Prepend arrow
$('.show-hide-list li .show-hide-list-content').hide();//Hide content
$('.show-hide-list h3').click(function() {//Perform toggle when clicked
$(this).next('.show-hide-list-content').toggle();
$(this).parent().find('.togglearrow').html('V ');
//V represents downward arrow
//Need to change orientation of prepended arrow when toggled
return false;
});
});
我建议不要使用:before
pseduo选择器或background-image
来创建箭头,而不要使用prepend
。 这是一个呈现性的内容,因此实际上应该由CSS处理。
使用:before
pseduo选择器的实时功能示例 -http: //jsfiddle.net/Nfw7y/
如果您需要更多控制箭头的外观,建议使用background-image
或图标字体 。
你可以简单地拥有
$('.show-hide-list h3 a').html( $('.show-hide-list h3 a').html().replace('>', 'V') );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.