Call a function when window is resized

2019-02-07 22:46发布

问题:

How can I call for this(or any) JS function to be run again whenever the Browser window is resized?

<script type="text/javascript">
 function setEqualHeight(e) {
     var t = 0;
     e.each(function () {
         currentHeight = $(this).height();
         if (currentHeight > t) {
             t = currentHeight
         }
     });
     e.height(t)
 }
 $(document).ready(function () {
     setEqualHeight($(".border"))
 })
</script>

回答1:

You can use the window onresize event:

window.onresize = setEqualHeight;


回答2:

You can subscribe to the window.onresize event (See here)

window.onresize = setEqualHeight;

or

window.addEventListener('resize', setEqualHeight);


回答3:

You use jquery, so bind it using the .resize() method.

$(window).resize(function () {
    setEqualHeight( $('#border') );
});


回答4:

This piece of code will add a timer which calls the resize function after 200 milliseconds after the window has been resized. This will reduce the calls of the method.

var globalResizeTimer = null;

$(window).resize(function() {
    if(globalResizeTimer != null) window.clearTimeout(globalResizeTimer);
    globalResizeTimer = window.setTimeout(function() {
        setEqualHeight();
    }, 200);
});