问题
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