Stuck with simple Javascript function to find height

怎甘沉沦 提交于 2019-12-11 02:55:58

问题


Anybody knows why the following code fails to work? I need a dynamic height for a fixed width div that may descend below past the viewport.

 <script type="text/javascript">
function findheight(){  
  var div = document.getElementById('bg');
  var height = document.scrollHeight;
  div.style.height = height + 'px';
}

  </script>     
</head>

<body onload="findheight()">
    <div id="bg"> 

Is there another way around this if not?? Any help is appreciated. Thanks


回答1:


You could achieve this using javascript, you have to use the 'offsetHeight' method.

function getHeight() {
    var height = document.getElementById('test').offsetHeight;
    alert(height);
}

Here is a sample fiddle
You can find the details here




回答2:


here is my solution for this kind of problem. hope this works for you too..

how to scale divs when i minimize browser so that divs dont collapse over each other

use $(document).height() from jquery to get document height




回答3:


The reason why this is not working is because the div.style.height is empty therefore doing parseFloat returns NaN

document.getElementById('bg').offsetHeight then this should work.

or try

function bodyHeight() {
var scnHei;

if (self.innerHeight) // all except Explorer
{
    scnHei = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
    // Explorer 6 Strict Mode
{
    scnHei = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
    scnHei = document.body.clientHeight;
}

document.getElementById("bgr_right").style.height=scnHei + "px";
document.getElementById("bgr_left").style.height=scnHei + "px";
}

in you body onload=bodyHeight();



来源:https://stackoverflow.com/questions/13099015/stuck-with-simple-javascript-function-to-find-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!