【学习篇】JavaScript可折叠区域

可折叠区域的基本思想:通过点击某个地方来显示或隐藏屏幕中的某个区域。

  

技术实现的关键:使用CSS的display特性,display特性的值有:none和block。none即为隐藏;block即为显示。

动手之前的设计:可折叠区域分为两个区域:标题栏和内容区域。标题栏总是可见的,内容部分是可以折叠或展开的。在页面上,可以使用两个<div>元素分别实现这个设计。

实现步骤:

在页面中插入<div>元素,并加入实现折叠功能的JS代码,代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
    <script type="text/javascript">
        function toggle(sDivId) {
            var oDiv = document.getElementById(sDivId);
            oDiv.style.display = (oDiv.style.display == "none") ? "block" : "none";
        }
    </script>
</head>
<body>
    <div style="background-color:Blue;color:White;font-weight:bold;padding:10px;cursor:pointer"
     onclick="toggle('divContent1')">Click Here</div>
    
     <div id="divContent1" style="border:3px solid blue;height:100px;padding:10px">
        This is some content to show and hide.
     </div>
     <p>&nbsp;</p>
    
     <div style="background-color:Blue;color:White;font-weight:bold;padding:10px;cursor:pointer"
      onclick="toggle('divContent2')">Click Here</div>
      <div id="divContent2" style="border:3px solid blue;height:100px;padding:10px">
        This is some content to show and hide.
      </div>
</body>
</html>

代码实现的效果,如下:

 

 

原文地址:https://www.cnblogs.com/jiangzhichao/p/1851009.html