1. 程式人生 > 程式設計 >js實現簡易點選切換顯示或隱藏

js實現簡易點選切換顯示或隱藏

本文例項為大家分享了js實現簡易點選切換顯示或隱藏的具體程式碼,供大家參考,具體內容如下

js實現簡易點選切換顯示或隱藏

html:

<div id="header">
 <p>點選切換顯示隱藏</p>
 <div class="close" onclick="closeTask()">關閉</div>
</div>
<div class="open" onclick="openTask()">開啟</div>

css:

* {
 margin:0;
 padding:0;
}
#header {
 width:100%;
 height:50px;
 background-color:cadetblue;
 text-align:center;
 color:white;
 position:relative;
 overflow:hidden;
 transition:all 0.5s;
}
#header>p {
 line-height:50px;
}
.close {
 position:absolute;
 right:5%;
 top:0;
 padding:10px;
 line-height:30px;
 cursor:pointer;
}
.open {
 position:absolute;
 right:5%;
 padding:10px;
 line-height:30px;
 background-color:cadetblue;
 cursor:pointer;
 transition:all 0.5s;
 color:white;
}

js:

var oDiv = document.getElementById("header");
var oOpen = document.getElementsByClassName("open");
var oDivheight = oDiv.offsetHeight;
var oOpenheight = oOpen[0].offsetHeight;
oOpen[0].style.top = `-${oOpenheight}px`;

function closeTask() {
 oDiv.style.height = "0";
 oOpen[0].style.top = "0";
}

const openTask = () => {
 oDiv.style.height = `${oDivheight}px`;
 oOpen[0].style.top = `-${oOpenheight}px`;

}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。