简体   繁体   中英

How can I change div height automatically on resize with javascript?

Now I have working on window load code, but can't make it work with window resize (height values will increase if I repeat the same function for resize event). Array is to show initial values after onload completed.

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);
     }
};

Here is 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>

Pure JavaScript solution is appreciated. Thanks in advance for a help!

You should re-organize your code to be able to repaint the whole screen any time, and hook on the resize event, see: JavaScript window resize event

Resize event is called also on mobile devices, when they change orientation.

<div id=div1></div>


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

same you can do with width.

it works for me ...

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM