gpt4 book ai didi

javascript - scrollHeight 不适用于位置 :absolute

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:44 25 4
gpt4 key购买 nike

我正在尝试检索主体的 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); }

仅仅将该位置更改为 relative 会使 javascript 函数返回正确的 scrollHeight 但出于其他原因我需要将其作为 absolute。如果某些元素是绝对定位的,scrollHeight 是否不起作用?正如我所说,后来还有另一个绝对定位元素,它对 scrollHeight 的返回值没有任何影响。只有作为 body 元素的第一个子元素的这个元素似乎是一个问题。有什么想法吗?

最佳答案

这有点肮脏,但你可以尝试这样做:

bg1.style.position = "relative"; 

var savedHeight = b.scrollHeight;

bg1.style.position = "absolute";

不确定这是否可行,但也许可以尝试一下。

关于javascript - scrollHeight 不适用于位置 :absolute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com