[英]change height of div by clicking it
我想通過單擊更改div的高度。
為什么第一次單擊卻不起作用?
我不知道為什么,但是div的高度為""
(由於else condition
,第二次單擊為20px
)
如果我在html元素中定義div的高度(style =“ height:20px”),則可以使用。
<html>
<head>
<script>
function divOpen() {
var divHeight= document.getElementById("divBottom").style.height;
if (divHeight=="20px") {
document.getElementById("divBottom").style.height="200px";
}
else {
document.getElementById("divBottom").style.height="20px";
}
}
</script>
<style>
div{
border:solid 1px gray;
width:200px;
height:20px;
}
.divBottom {
position: fixed;
bottom: 0;
right: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="divBottom" id="divBottom" onclick="divOpen()"></div>
</body>
</html>
因此我知道如何修復它,但是我不知道為什么第一次單擊時高度為空。
請告訴我..
任何幫助表示贊賞!
最初單擊時,div的height
樣式屬性為''
因為尚未設置。
通過style屬性和使用類來設置高度之間是有區別的。 嘗試重構您的代碼,並使其使用offsetHeight
而不是style.height
。
的JavaScript
function divOpen() {
var divHeight= document.getElementById("divBottom").offsetHeight;
console.log(divHeight);
//22 because of the border
if (divHeight == 22) {
document.getElementById("divBottom").style.height="200px";
}
else {
document.getElementById("divBottom").style.height="20px";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.