[英]Change display style property of a div using Javascript
我試圖通過更改div的style屬性來顯示btn的div onclick。 但是我看不懂那個div的display屬性。 我在某處讀到代碼不起作用,因為腳本試圖在div加載之前獲取值,因此應在window.onload之后觸發腳本。 如何在窗口加載后但僅在單擊按鈕后才使腳本工作?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#hidden-div{
display: none;
}
</style>
<script type="text/javascript">
function showMe() {
var foo = document.getElementById('hidden-div');
alert(foo.style.display); //this gives a blank alert
if(foo.style.display == ''){
foo.style.display = 'block';
}
else {
foo.style.display == 'none';
}
}
</script>
</head>
<body>
<input type="button" id="btn-me" onclick="showMe()">+ clicking here should display the checkboxes</input><br>
<div id="hidden-div">
<input type="checkbox" id="check-1"> Check 1</input>
<br>
<input type="checkbox" id="check-2"> Check 2</input>
<br>
<input type="checkbox" id="check-3"> Check 3</input>
</div>
</body>
</html>
注意事項: ==
用於比較, =
用於分配。 另外,沒有結束輸入標簽。 這是完成的代碼段:
function showMe() { var foo = document.getElementById('hidden-div'); if(foo.style.display == '' || foo.style.display == 'none'){ foo.style.display = 'block'; } else { foo.style.display = 'none'; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <input type="button" id="btn-me" onclick="showMe()">+ clicking here should display the checkboxes</input><br> <div id="hidden-div" style="display:none;"> <input type="checkbox" id="check-1"> Check 1 <br> <input type="checkbox" id="check-2"> Check 2 <br> <input type="checkbox" id="check-3"> Check 3 </div> </body> </html>
我也改變了一些邏輯。 如果沒有display
,並且單擊了按鈕,請切換可見性。 如果display
不為空,則不display
。
這是element.style.<style>
,僅當樣式設置為內聯時才可訪問。
foo.style.display
僅適用於內聯設置的樣式,不適用於stylehseets或block。 為此,您可以使用getComputedStyle
:
function showMe() { var elem = document.getElementById("hidden-div"); var foo = window.getComputedStyle(elem, null); if (foo.getPropertyValue("display") == 'none') { elem.style.display = 'block'; } else { elem.style.display = 'none'; } }
#hidden-div { display: none; }
<input type="button" id="btn-me" onclick="showMe()">+ clicking here should display the checkboxes <br> <div id="hidden-div"> <input type="checkbox" id="check-1"> Check 1 <br> <input type="checkbox" id="check-2"> Check 2 <br> <input type="checkbox" id="check-3"> Check 3 </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.