[英]scrollHeight not working with position:absolute
我正在嘗試檢索主體的scrollHeight
以重置 id="background1" 的 div 的大小。 如果在我的外部 css 我將該 id 設置為position:absolute
scrollHeight
總是返回 0。如果我將它設置為position:relative
scrollHeight
給我正確的值。 在 css 中當然還有更多選擇器,其中一個設置為position:absolute
- 保留它不會改變上述行為。 編碼:
<script type="text/javascript">
function getElement(elem) {
var art;
if ( document.all ) { // this is the way old msie versions work
art = document.all[elem];
}
else if ( document.layers ) { // this is the way nn4 works
art = document.layers[elem];
}
else if ( document.getElementById ) { // this is the way the standards work
art = document.getElementById( elem );
}
return art;
}
function toggleArticleDisplay(elem) {
var artArray = document.getElementsByTagName("article");
for(var i = 0; i < artArray.length; i++) {
artArray[i].style.display = "none";
}
var art = getElement(elem);
art.style.display = "block";
var bg1 = document.getElementById("background1");
bg1.style.height = "550px";
var b = document.getElementById("potoococha");
alert(b.scrollHeight);
bg1.style.height = (b.scrollHeight >= window.innerHeight) ?
(b.scrollHeight+20) + "px" : window.innerHeight + "px";
}
</script>
</head>
<body id="potoococha" onLoad="toggleArticleDisplay('homeText')">
<div id="background1" style="height:615px;"/>
現在是 css:
div#background1 { position : absolute;
left : 45px;
top : 0px;
z-index : 1;
width : 50px;
background-color : rgba(182,181,91,1.0); }
僅將 position 更改為相對值會使 javascript function 返回正確的scrollHeight
但出於其他原因我需要將其作為absolute
。 如果某些元素是絕對定位的, scrollHeight
是否不起作用? 正如我所說,后面還有另一個絕對定位元素, scrollHeight
的返回值沒有任何影響。 只有這個作為 body 元素的第一個子元素的元素似乎是一個問題。 有任何想法嗎?
這有點骯臟,但你可以嘗試這樣做:
bg1.style.position = "relative";
var savedHeight = b.scrollHeight;
bg1.style.position = "absolute";
不確定這是否會起作用,但也許可以嘗試一下。
我已經解決了控制變量的問題
document.scrollingElement.scrollHeight
代替
document.body.scrollHeight
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.