scrollHeight不与position:absolute一起工作

scrollHeight not working with position:absolute

本文关键字:一起 工作 absolute 不与 position scrollHeight      更新时间:2023-09-26

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

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

这是一个肮脏的hack,但是你可以试着这样做:

bg1.style.position = "relative"; 
var savedHeight = b.scrollHeight;
bg1.style.position = "absolute";

不知道这是否可行,但不妨试一试。

我已经解决了控制变量

的问题
document.scrollingElement.scrollHeight

代替

document.body.scrollHeight