当窗口大小改变时,jQuery不会执行

时间:2017-11-26 12:11:21

标签: javascript jquery

我只是编写一个脚本来自动定位页面上的元素。

$(document).ready(function(){   
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();
        if (scroll < 180) {
            $(".header-bottom").removeClass("scroll-menu");
            if ($(window).width() > 991) {
                $(".header_user_top").css("position", "absolute");
                $(".header_user_top").css("top", "initial");
                $(".header_user_top").css("right", "60px");
                $(".header_user_top").css("z-index", "1");
            }
        } else {
            $(".header-bottom").addClass("scroll-menu");
            if ($(window).width() > 991) {
                var rightContainer = ($(window).width() - ($('#header div.header-bottom div.container').offset().left + $('#header div.header-bottom div.container').outerWidth()));
                $(".header_user_top").css("position", "fixed");
                $(".header_user_top").css("top", "-22px");
                $(".header_user_top").css("right", rightContainer+60+"px");
                $(".header_user_top").css("z-index", "99");
            }
        }
    });
});

它正常工作,但如果我调整浏览器窗口大小,脚本就不会重新加载。

如果我刷新页面它正在运行。

我已将window.onresize = function(){ location.reload(); }添加到我的脚本中以解决此问题,但我正在寻找更好的解决方案。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

使用on函数调用多个事件:

   $(window).on("load resize scroll",function(e){
    // do something
    }

答案 1 :(得分:2)

调用在windows.resize上处理大小的函数

function handleSize(){
   // You code to handle size
 }
window.resize=handleSize();
相关问题