我有一个div的图像背景,高度是100%,所以它填补任何设备上的屏幕。在屏幕底部是一个导航条。当页面被滚动时,我希望导航条能固定在离顶部一定距离的屏幕顶部。我试过使用这个JavaScript:
$(window).scroll(function(){
if ($(this).scrollTop() > 587) {
$('.hnav').addClass('hfixed');
} else {
$('.hnav').removeClass('hfixed');
}});它在我的屏幕上工作得很好,但在任何其他屏幕上都不行,因为由于100%的高度图像,导航会根据窗口大小改变距离。
无论窗口大小如何,如果从顶部设置的距离,如何使导航定位到位??
谢谢
发布于 2015-06-10 19:14:44
您可以使用element.getBoundingClientRect()获取元素的位置,因此,一旦返回最大值0,就可以添加'hfixed‘类:
var nav = $('.hnav');
var pos = nav.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos + 50 >= pos.top) {
nav.addClass("hfixed");
} else {
nav.removeClass("hfixed");
}
});编辑:
在calc中增加了50 an的额外保证金,因为顶部的栏。
编辑2:
更改了示例,现在它基于这
编辑3:
添加50 to边距,因为新示例中的顶部栏
https://stackoverflow.com/questions/30764852
复制相似问题