jQuery resize event not firing

前端 未结 7 1585
独厮守ぢ
独厮守ぢ 2021-01-11 09:58

For whatever reason the following:

$(function() {
  $(window).resize(function() {
    alert(\"resized!\");
  });
});

only fires an event wh

7条回答
  •  不要未来只要你来
    2021-01-11 10:49

    it is best to avoid attaching to events that could potentially generate lots of triggering such as the window resize and body scroll, a better approach that flooding from those events is to use a timer and verify if the even has occurred, then execute the proper action, something like this:

    $(function() {
        var $window = $(window);
        var width = $window.width();
        var height = $window.height();
    
        setInterval(function () {
            if ((width != $window.width()) || (height != $window.height())) {
                width = $window.width();
                height = $window.height();
    
                alert("resized!");
            }
        }, 300);
    });
    

    another advantage doing it using timer is you have full control of how often to check, which allows you flexibility if you have to consider any additional functionality in the page

提交回复
热议问题