- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Bootstrap 3,我有一个全屏旋转木马,后面有一个导航栏。用户完全滚动经过轮播后,导航栏会固定在顶部。这很好用。
但是现在当用户几乎不向下滚动然后向上滚动时,导航栏不会回到原来的位置,它会固定在顶部。
这是我的 js:
$(function() {
var lastfixed = undefined,
spacerEl = undefined,
fixed = false,
ghostElHeight = 0;
$(document).on('scroll', function() {
console.log('scroll top : ' + $(window).scrollTop());
if ($(window).scrollTop() >= $(".carousel").outerHeight()) {
fixed = true;
if (fixed === lastfixed) return
$(".navbar").addClass("navbar-fixed-top");
ghostElHeight = $(".navbar").outerHeight()
if (!!!spacerEl) {
spacerEl = $(".navbar").after(
'<div class="navspacer" style="height:' + ghostElHeight + 'px"> </div>').next();
}
}
if ($(window).scrollTop() < $(".carousel").height() + ghostElHeight) {
fixed = false;
if (fixed === lastfixed) return
ghostElHeight = 0;
$(".navbar").removeClass("navbar-fixed-top");
!!spacerEl && spacerEl.remove();
spacerEl = undefined;
}
lastfixed = fixed;
});
});
我还创建了一个 fiddle :http://jsfiddle.net/thqx9g9b/2/为了重现错误,您可能需要单击滚轮,在导航栏固定到顶部后向下滚动一点点,然后向上滚动。
奇怪的是我正在做同样的事情,但是有一个全屏超大屏幕并且没有出现错误。
更新:如果我在 .carousel 类上添加“padding:55px”,问题就会消失。但是,如果我在轮播中使用图像,这会导致出现大边框。
这是带有填充的更新 fiddle :http://jsfiddle.net/thqx9g9b/3/
这在我的带有超大屏幕的版本上有效的原因是因为图像设置在父 div 上并且没有由填充引起的边框,我试图在旋转木马内的各种元素上放置填充但是对于它需要在父 div 上才能工作,有人对此有某种解决方法吗?还是我遗漏了什么?
最佳答案
目前您的算法似乎有点偏差。
现在,如果您只滚动到低于 $(".carousel").outerHeight() 一点
-> fixed 不成立,因此导航栏永远不会丢失 navbar-fixed-top
类。
你必须改变这个
if ($(window).scrollTop() < $(".carousel").height() + ghostElHeight) {
到
if ($(window).scrollTop() < $(".carousel").height()) {
然后它按预期工作。当然你不必再乱用 ghostElHeight
了。只需在 HTML 中添加 navspacer 并使用显示/隐藏切换它。
还有一个问题:你引入了一个变量lastfixed
,这使得代码变得复杂。没有 lastfixed
的更好方法:
改变你的算法
fixed = true;
if (fixed === lastfixed) return
到
if (fixed == true) return
fixed = true;
假部分也一样。这更容易也更清楚。
完整的JS代码:
$(function () {
var fixed = false;
$(document).on( 'scroll', function(){
if($(window).scrollTop()>=$(".carousel").outerHeight())
{
if (fixed == true) return
fixed = true;
$(".navbar").addClass("navbar-fixed-top");
$(".navspacer").show();
}
if($(window).scrollTop()<$(".carousel").height())
{
if (fixed == false) return
fixed = false;
$(".navbar").removeClass("navbar-fixed-top");
$(".navspacer").hide();
}
});
});
并在导航栏之后手动添加navspacer:
<div style="height:100px; display: none;" class="navspacer"> </div>
关于jquery - Ghost dom element navbar fixed top不停留在原位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844980/
我是一名优秀的程序员,十分优秀!