簡體   English   中英

JavaScript隱藏和顯示切換,隱藏DIV

[英]JavaScript hide and show toggle, hide DIV

對於以下示例,我如何通過隱藏默認情況下當前顯示的“ divToToggle” DIV來開始頁面? 我不想使用“ display:none;” 出於可訪問性原因而在腳本之外。 啟動時如何在腳本中隱藏“ divToToggle”? 謝謝。

            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
            <html>
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <title>JavaScript hide and show toggle</title>
            <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
            </head>
            <body>
            <script>
            function toggleAndChangeText() {
                 $('#divToToggle').toggle();
                 if ($('#divToToggle').css('display') == 'none') {
                      $('#aTag').html('[+] Show text');
                 }
                 else {
                      $('#aTag').html('[-] Hide text');
                 }
            }
            </script>
            <br>
            <a id="aTag" href="javascript:toggleAndChangeText();">[-] Hide text</A> 
            <div id="divToToggle">Content that will be shown or hidden.</div>
            </body>
            </html>

只需使用jQuery,因為您已經在使用它(並且這種方式不會阻止非JS用戶看到該元素):

function toggleAndChangeText() {
     $('#divToToggle').toggle();
     if ($('#divToToggle').css('display') == 'none') {
          $('#aTag').html('[+] Show text');
     }
     else {
          $('#aTag').html('[-] Hide text');
     }
}

$('#divToToggle').hide();
// the rest of your script(s)...

另外,對切換功能進行了較小的更新:

function toggleAndChangeText() {
    // because you're accessing this element more than once,
    // it should be cached to save future DOM look-ups
    var divToToggle = $('#divToToggle');
    divToToggle.toggle();
    // You're not changing the HTML, just the text, so use the
    // appropriate method (though it's a *minor* change)
    $('#aTag').text(function() {
        // if the element is visible change the text to
        // '...hide...'; if not, change the text to '...show...'
        return divToToggle.is(':visible') ? '[-] Hide text' : '[+] Show Text';
    });
}

參考文獻:

只需在document.ready函數中使用hide函數

$(function(){
     $('#divToToggle').hide();
});

暫無
暫無

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

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