用js控制div的顯示與隱藏

weixin_33807284發表於2016-02-19

功能介紹:要實現一個div的顯示與隱藏,方法有很多,這裡記錄下一個簡單的js效果,用js來控制div的顯示與隱藏,示例程式碼如下:

<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title>js顯示隱藏層</title>
<script language="JavaScript" type="text/JavaScript">
function showdiv(targetid,objN){
   
      var target=document.getElementById(targetid);
      var clicktext=document.getElementById(objN)

            if (target.style.display=="block"){
                target.style.display="none";
                clicktext.innerText="Open DIV";
  

            } else {
                target.style.display="block";
                clicktext.innerText='Close DIV';
            }
   
}
</script>
<style type="text/css">
    body { font: normal 14px "宋體" }
    a { text-decoration: none; display: block;background-color:#ABCDEF;height: 20px;}
    a:hover{background-color: #CCC;}
    #showtext { cursor: hand; cursor:pointer;}
    #showtext2 { cursor: hand; cursor:pointer;}
    #contentid { margin-top: 10px; width:100%; border: 1px solid #CCC; background: #F1F1F1; padding: 15px; }
    #contentid2 { margin-top: 10px; width: 470px; border: 1px solid #CCC; background: #F1F1F1; padding: 15px; }
    .none { display: none; }
</style>
</head>
<body>
    <a id="showtext" onClick="showdiv('contentid','showtext')">Open DIV1</a>
    <div id="contentid" class="none">開啟的內容</div>
    <br/><br/>
    <a id="showtext2" onClick="showdiv('contentid2','showtext2')">Open DIV2</a>
    <div id="contentid2" class="none">1<br />
    </div>
</body>
</html>

另外一個簡單的展開與伸縮效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js展示與收起效果</title>
    <style>
        *{margin: 0;padding: 0;}
        #content{height:auto;width: 500px;margin:0 auto;font-size: 14px;padding:5px;
            background-color: #8c8c8c;}
        .slide{margin:0 auto;padding:0;width: 500px; border-top: solid 2px grey;}
        .more_slide{background-color:#8c8c8c;text-align:center;width: 100px;margin-top:0 auto;text-decoration: none;height:30px;padding:10px 0 0 0;display:block;}
    </style>
    <script type="text/javascript">
        function showdiv()
        {
            document.getElementById('hide').style.display="block";
            document.getElementById('more').innerHTML="收起";
            document.getElementById('more').href="javascript:hidediv()";
        }
        function hidediv()
        {
            document.getElementById('hide').style.display="none";
            document.getElementById('more').innerHTML="更多選項";
            document.getElementById('more').href="javascript:showdiv()";
        }
    </script>
</head>
<body>
<div id="content">
    <p>展示區域</p>
    <p>新聞列表</p>
    <div id="hide" style="display: none">
        <p>這裡是隱藏區域</p>
        <p>Internet is handsome</p>
        <p>today is weekend</p>
    </div>
</div>
<p class="slide">
    <a href="javascript:showdiv()" id="more" class="more_slide">更多選項</a>
</p>
</body>
</html>

相關文章