【问题标题】:How to use Javascript or Jquery to toggle the visibility of a html div如何使用 Javascript 或 Jquery 切换 html div 的可见性
【发布时间】:2014-01-02 15:25:55
【问题描述】:

我正在创建一个基本站点,并且我有以下隐藏 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 是 + 符号的图标

单击 + 图标后,如何将 + 图标更改为 - 图标?

谢谢。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    将显示设置为无

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

    演示:Fiddle

    【讨论】:

    • 谢谢你,效果很好。我在原始问题中添加了更多内容。我有一个 + 符号图标,所以现在当我点击它时,我的文字就会出现。这很好,但 + 图标仍然存在。如何将图标更改为 - 图标?再次感谢。
    • 添加在原始问题的底部。这是实际的行: 显示/隐藏说明
    【解决方案2】:

    使用简单的 CSS :

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

    【讨论】:

      【解决方案3】:

      你有 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
      });
      

      【讨论】:

        猜你喜欢
        • 2014-03-02
        • 1970-01-01
        • 2018-12-17
        • 2013-07-12
        • 2010-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-15
        相关资源
        最近更新 更多