我有 <header>
和 <nav>
受 JavaScript 影响的 block 。我想要的是 <nav>
block 变成position: static
如果用户将窗口大小调整为小于 1119 像素宽。该脚本目前仅适用于页面加载,但不检测调整大小。
我尝试应用 this question 中的解决方案,但没有运气。以下是相关网页的链接:
到目前为止,这是我的 JavaScript:
<script>
$(document).ready(function(){
var $window = $(window);
function checkWidth() {
windowsize = $window.width();
if (windowsize > 1119) {
$(window).scroll(function() {
if ($(this).scrollTop()>119)
{
$('header').fadeOut();
$('nav').css({position: 'fixed', top: '0px'});
}
else
{
$('header').fadeIn();
$('nav').css({position: 'absolute', top: 'auto'});
}
});
}
else {
$('nav').css({position: 'static', top: '0px'});
}
}
// can trigger the resize handler instead of
// explicitly calling checkWidth()
$(window).resize(checkWidth).resize();
});
</script>
最佳答案
使用.trigger()为此:
$(window).resize(checkWidth)
.trigger('resize');
尝试关注 demo 强>。当您打开控制台时,尝试在控制台中调整窗口大小时,只要您调整窗口大小时,就会输出日志。
在您的服务器中尝试此代码:
$(document).ready(function(){
var $window = $(window);
$window.on('resize', function () {
windowsize = $window.width();
if (windowsize > 1119)
{
$window.scroll(function() {
if ($(this).scrollTop()>119)
{
$('header').fadeOut();
$('nav').css({position: 'fixed', top: '0px'});
}
else
{
$('header').fadeIn();
$('nav').css({position: 'absolute', top: 'auto'});
}
}).scroll();
}
else
{
$('nav').css({position: 'static', top: '0px'});
$('header').fadeIn();
$window.off('scroll');
}
}).resize();
});
关于javascript - 使用 JavaScript/jQuery 响应窗口大小调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21113413/