js控制div點選隱藏顯示
阿新 • • 發佈:2019-01-28
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/"/> <title>點選切換</title> <style type="text/css"> #thediv { width: 200px; height: 50px; background: #ccc; display: none; } </style> <script type="text/javascript"> window.onload = function () { var obt = document.getElementById("bt"); var odiv = document.getElementById("thediv"); function getStyle(obj, attr) { // 誰的 那個屬性 if (obj.currentStyle) // ie 等 { return obj.currentStyle[attr]; } else { return window.getComputedStyle(obj, null)[attr]; // w3c 瀏覽器 } } //console.log(getStyle(odiv, 'display')); obt.onclick = function () { //獲取的樣式需要寫在點選事件裡面,寫在外面只能獲取一次,不能動態獲取, if (getStyle(odiv, 'display') == "none") { odiv.style.display = "block"; obt.value = "隱藏模組"; } else { odiv.style.display = "none"; obt.value = "顯示模組"; } } } </script> <body> <input type="button" id="bt" value="顯示模組"/> <div id="thediv"></div> </body> </html>
以上為第一種
以上為第二種<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/"/> <title>點選切換</title> <style type="text/css"> #thediv { width: 200px; height: 50px; background: #ccc; display: none; } </style> <script type="text/javascript"> window.onload = function () { var obt = document.getElementById("bt"); var odiv = document.getElementById("thediv"); obt.onclick = function () { if (odiv.style.display== "block") { //第一判斷時將none改為block即可避免第一次點選無效的問題 odiv.style.display = "none"; obt.value = "顯示模組"; } else { odiv.style.display = "block"; obt.value = "隱藏模組"; } } } </script> <body> <input type="button" id="bt" value="顯示模組"/> <div id="thediv"></div> </body> </html>
以上為第三種<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> <style type="text/css"> #thediv{ width:200px; height:50px; background:#ccc; } </style> <script type="text/javascript"> window.onload=function(){ var obt=document.getElementById("bt"); var odiv=document.getElementById("thediv"); obt.onclick=function(){ if(odiv.style.display=="none"){ odiv.style.display="block"; obt.value="隱藏模組"; } else{ odiv.style.display="none"; obt.value="顯示模組"; } } } </script> <body> <input type="button" id="bt" value="顯示模組"/> <div id="thediv" style="display:none"></div> </body> </html>