簡體   English   中英

在Jquery中切換時如何更改前置文本?

[英]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>&gt;&nbsp;</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('&gt;&nbsp;');  
        } else {
            arrow.html('V&nbsp;');
        }
        //Need to change orientation of prepended arrow when toggled
        return false;
    });
}); ​

http://jsfiddle.net/6DB7t/1/

您可以將一個類應用於該箭頭,前提是您的用戶的瀏覽器將支持該箭頭。 從這樣的一些CSS開始:

-webkit-transform: rotate(-270deg); 
-moz-transform: rotate(-270deg);

或者,只需切換向下箭頭圖像的可見性,即可在任何現代瀏覽器上使用。

只需將箭頭放在<span>並為其指定適當的類,以便稍后可以再次找到它:例如,如下所示:

$(document).ready(function(){

$('.show-hide-list h3 a').prepend('<span class="togglearrow">&gt;&nbsp;</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('&gt;', 'V') );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM