Call a function when window is resized

天涯浪子 提交于 2019-11-29 11:06:17

问题


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


来源:https://stackoverflow.com/questions/15205609/call-a-function-when-window-is-resized

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