作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在此网站上:编辑
我希望在您滚动过去后将 $("#menu")
附加到页面顶部,有点像这里的标题:http://starwars.ea.com/starwars/battlefront
问题是当我这样做时,页面会跳起来。我以为我可以用 $("#placeHolder")
解决这个问题,但这也不起作用。
我怎样才能像在前线网站上那样做到这一点?
我的 jquery(带有去抖功能)如下
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
$(window).scroll(function() {
var myEfficientFn = debounce(function() {
if($(window).scrollTop() > $("#menu").height())
{
$("#menu").addClass("fixed");
}
else
{
$("#menu").removeClass("fixed");
}
}, 250);
myEfficientFn();
});
谢谢!
最佳答案
使 #menu
的宽度为 100%。
此外,将 #menu
的原始偏移量(在页面加载时)存储在一个变量中,并在应用 fixed
类时测试窗口是否滚动超过该值:
var fromTop = document.getElementById('menu').getBoundingClientRect().top;
$(window).scroll(function(){
if($(window).scrollTop() > fromTop)
$("#menu").addClass("fixed");
else
$("#menu").removeClass("fixed");
})
根据需要添加去抖。
我只是从某人的 CSS 相关问题中使用它,并将您的代码添加到其中作为一个工作示例:http://jsfiddle.net/fzhg4cof/2/
关于jquery - 将元素设置到位置 :Fixed Results In Ugly Page Jump,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29733247/
我是一名优秀的程序员,十分优秀!