2012-11-15 221 views
1

對於以下示例,我將如何通過隱藏「divToToggle」DIV來啓動頁面,因爲它當前默認顯示?我不想使用'display:none'出於可訪問性的原因在腳本之外。如何在啓動腳本中隱藏'divToToggle'? 謝謝。JavaScript隱藏並顯示切換,隱藏DIV

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

回答

0

只需使用隱藏功能的document.ready功能

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

謝謝大衛和wirey內。 我後來的是隱藏功能,但不知道如何正確標記它,謝謝你的snippet有瑕疵。 – C0111N5

0

只需使用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'; 
    }); 
} 

參考文獻: