当我取出窗口宽度的检查时,此代码有效。一旦我添加了对窗口宽度的引用,代码就不再起作用。我只希望导航栏固定在小于 768px 的屏幕尺寸上。我对 jQuery 很生疏,所以非常感谢您的帮助。
$(document).ready(function() {
var width = $(window).width();
$(window).scroll(function() {
if ($(width) < 768) {
if ($(this).scrollTop() > 567) {
$('.navbar').css('position', 'fixed').css('top', '0');
} else {
$('.navbar').css('position', 'relative');
}
} else {
$('.navbar').css('position', 'relative');
}
})
$(window).resize(function() {
if ($(width) < 768) {
if ($(this).scrollTop() > 567) {
$('.navbar').css('position', 'fixed').css('top', '0');
} else {
$('.navbar').css('position', 'relative');
}
} else {
$('.navbar').css('position', 'relative');
}
});
});
最佳答案
这里的主要问题是,当没有必要时,您将 width
放置在 jQuery 对象中。只需在条件中直接使用 width
即可:
if (width < 768)
话虽这么说,您的代码可以是 DRY 的,也可以通过使用 CSS 类和媒体查询来改进。试试这个:
jQuery(function($) {
$(window).on('scroll resize', function() {
$('.navbar').toggleClass('fixed', $(this).scrollTop() > 567);
});
});
html,
body {
height: 2000px;
padding: 0;
margin: 0;
}
.navbar {
padding: 10px;
background-color: #CCC;
}
@media only screen and (max-width: 768px) {
.navbar.fixed {
position: fixed;
top: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">Navbar</div>
关于javascript - 为什么导航栏不能固定到顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59738228/