2016-07-27 287 views
1

当我向下滚动到我的网站时,我想让我的标题降低其高度。所以我写了这个代码:调整窗口大小Jquery

function resizeHeader() { 
    if ($(window).width() > 1200) { 
     if ($('body').hasClass('scrolled')) { 
      $('#masthead .top-header').css('height', '50px'); 
     } else { 
      //Initial height 
      $('#masthead .top-header').css('height', 'auto'); 
     } 
    } else if ($(window).width() > 768 && $(window).width() < 989) { 
     if ($('body').hasClass('scrolled')) { 
      $('#masthead .top-header').css('height', '35px'); 
     } else { 
      $('#masthead .top-header').css('height', 'auto'); 
     } 
    } 
} 

/** Fix header scroll **/ 
$(window).scroll(function() { 
    if ($(this).scrollTop() > 1) { 
     $('body').addClass('scrolled'); 
     resizeHeader(); 
    } else { 
     $('body').removeClass('scrolled'); 
     resizeHeader(); 
    } 
}); 

所以此代码的工作,当我刷新我的网页在想要的大小,脚本工作。

然而,当我刷新,然后我调整我的窗口,那么我的头有没有我这个大小设置高度

我想,当我调整我的窗口,该功能正在运行,并做动作。它在刷新我的页面时总是在工作,而不是在调整它的大小时。

感谢您的帮助!

+0

正如Rory所建议的那样,您最好使用[CSS媒体查询](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) –

回答

2

您需要在加载页面时触发scroll事件,以便运行代码。试试这个:

$(window).scroll(function() { 
    // your code here... 
}).trigger('scroll'); // < trigger on load 

另外请注意,这将是更为合适的使用媒体查询,像这样把你resizeHeader()功能的逻辑中,以一个负责任的CSS样式表:

#masthead .top-header { 
    height: auto; 
} 

@media (max-width: 1200px) { 
    .scrolled #masthead .top-header { 
    height: 50px; 
    } 
} 

@media (max-width: 989px) { 
    .scrolled #masthead .top-header { 
    height: 35px; 
    } 
} 
var scrollTimer; 
$(window).scroll(function() { 
    clearTimeout(scrollTimer); 
    scrollTimer = setTimeout(function() { 
     $('body').toggleClass('scrolled', $(this).scrollTop() > 1); 
    }, 250); 
}).trigger('scroll'); 
+0

我认为OP希望绑定resize事件确实:“我想要的是当我调整窗口大小时,函数正在运行并执行操作 –

+0

是的,我忘了我可以通过响应媒体查询来实现这一点,我正在尝试这个解决方案 –

+0

是的它适用于媒体查询。非常感谢提醒! –