0

现在我正在处理窗口加载代码,但不能使它与窗口调整大小一起工作(如果我对调整大小事件重复相同的函数,高度值会增加)。数组是在onload完成后显示初始值。

var arr = [];

window.onload = function() {
    var newsBlocks = document.getElementsByClassName('news');
    for (var i = 0; i < newsBlocks.length; i++) {
      var newsBlock = newsBlocks[i];
      var left = newsBlock.getElementsByTagName('article')[0];
      var right = newsBlock.getElementsByTagName('article')[1];
      var height = Math.max(left.offsetHeight, right.offsetHeight);
      left.style.height = right.style.height = height.toString() + 'px';
      arr.push(left.style.height);
      console.log(arr);
     }
};

这是html:

<div class="main">
    <section class="news">
        <article>
            <a href="#" class="news-image"><img src="images/t.png"></a>
            <h2><a href="#">Heading</a></h2>
            <a href="#" class="description">test text</a>
        </article>
        <article>
            <a href="#" class="news-image"><img src="images/t.png"></a>
            <h2><a href="#">Heading</a></h2>
            <a href="#" class="description">a lot of test text here</a>
        </article>
</div>

纯 JavaScript 解决方案值得赞赏。提前感谢您的帮助!

4

3 回答 3

0

try the following code. It is working for me.

var buffer = 20; //scroll bar buffer
var divId = document.getElementById('yourDivID');

function pageY(elem) {
    return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}

function resizeDiv() {
    var height = document.documentElement.clientHeight;
    height -= pageY(divId) + buffer;
    height = (height < 0) ? 0 : height;
    divId.style.height = height + 'px';
}

window.onresize = resizeDiv;
于 2013-09-25T09:10:08.187 回答
0

您应该重新组织您的代码,以便能够随时重新绘制整个屏幕,并挂钩resize事件,请参阅:JavaScript window resize event

当移动设备改变方向时,也会调用调整大小事件。

于 2013-09-25T09:04:13.040 回答
0
<div id=div1></div>


<script>
div1.style.height = (your preffered height)
</script>

你可以对宽度做同样的事情。

这个对我有用 ...

于 2013-09-25T09:07:43.780 回答