简体   繁体   English

JavaScript隐藏和显示切换,隐藏DIV

[英]JavaScript hide and show toggle, hide DIV

For the following example, how would I start the page off by hiding the 'divToToggle' DIV as it is currently showing on default? 对于以下示例,我如何通过隐藏默认情况下当前显示的“ divToToggle” DIV来开始页面? I do not want to use 'display:none;' 我不想使用“ display:none;” outside of the script for accessibility reasons. 出于可访问性原因而在脚本之外。 How do you hide the 'divToToggle' within the script on startup? 启动时如何在脚本中隐藏“ divToToggle”? Thanks. 谢谢。

            <!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>

Just use jQuery, since you're already using it (and this way doesn't prevent non-JS users from seeing the element): 只需使用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)...

Also, a minor update to your toggle function: 另外,对切换功能进行了较小的更新:

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';
    });
}

References: 参考文献:

Just use the hide function inside a document.ready function 只需在document.ready函数中使用hide函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM