簡體   English   中英

如何使用Javascript或Jquery切換html div的可見性

[英]How to use Javascript or Jquery to toggle the visibility of a html div

我正在創建一個基本站點,並且具有隱藏div的以下腳本:

<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>

<a href="#" onclick="toggle_visibility('description');">Show/Hide Description</a>

<div id="description">
<br>
<br>
<p>This is a test paragraph</p>
</div>

當我加載頁面時,默認是顯示文本。 每次加載頁面時,如何在div中隱藏文本?

我希望用戶手動單擊按鈕以查看文本。

編輯:

現在,我添加了帶有+符號的圖片,以便用戶可以單擊+,並使用以下幾行顯示該文本:

  <h4>Backstory</h4> 

  <img alt="" style="width: 20px; height: 20px;" src="./images/headerExpand.png" a href="#" onclick="toggle_visibility('backstory');">Show/Hide Description</a>

<div id="backstory" style="display: none">
<br>
   <p>This is a new block of text</p>
</div>

./images/headerExpand.png是+符號的圖標

單擊+圖標后,如何將+圖標更改為-圖標?

謝謝。

將顯示設置為無

<div id="description" style="display: none">

重新設計的解決方案可能看起來像

<!-- Add a class toggler and the id of the target element as the href-->
<a href="#description" class="toggler">Show/Hide Description</a>

<!-- Add a class hidden so that the element is hidden when the page loads -->
<div id="description" class="hidden">
    <br/>
    <br/>
    <p>This is a test paragraph</p>
</div>

CSS

.hidden {
    display: none;
}

然后jQuery腳本

// dom ready handler
jQuery(function () {
    //register a click handelr for all anchor elements with class toggler
    $('a.toggler').click(function (e) {
        //prevent the default action of the event
        e.preventDefault();
        //togger the visibility of the element targetted by the href
        $($(this).attr('href')).toggle()
    });
})

演示: 小提琴

使用CSS:

<p style="display:none;">This is a test paragraph</p>

您有2個選項,像其他答案一樣在html中設置css屬性

<div id="description" style="display: none">

或將您的JavaScript包裝在某種東西中,以告知頁面在頁面加載時運行Stript

使用jQuery

$(document).ready(function(){
   //your code
});

要么

$(function(){
  //your code
});

或常規的舊javascript

window.onload = function(){
  //your code
});

暫無
暫無

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

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