我的问题是使用.offset()找到浏览器的y位置,有一次我想把类添加到我的div中,我想创建像yourkarma.com这样的东西(看看什么是增强IT的部分)
$(document).ready(function() {
$(window).scroll(function (event) {
// what the y position of the scroll is
var z = '150';
var x = $('#thisdiv').offset().top - z;
var y = $(this).scrollTop();
// whether that's below the form
if (y >= x) {
// if so, ad the fixed class
$('#thisdiv').addClass('red');
}
});
})我走对路了吗?我觉得使用z=150并将其减去X是一种很便宜的方式。有没有办法让它变得更好?
发布于 2013-03-14 10:35:02
这并不便宜,但也许更清晰有效的方法是:
var $thisdiv = $('#thisdiv');
var thisdiv_top = $thisdiv.offset().top - 150;
var thisdiv_flag = false;
$(window).scroll(function (event) {
if(thisdiv_flag) return;
// what the y position of the scroll is
var y = $(window).scrollTop();
// whether that's below the form
if (y >= thisdiv_top) {
// if so, ad the fixed class
$thisdiv.addClass('red');
thisdiv_flag = true;
}
});我不太清楚为什么-150。我想是这样的,在元素出现之前,它会更快地触发。但是这段代码的效率要高一点。它缓存div的jQuery对象,并设置一个标志,这样事件就不会再次触发。它还避免了每次用户滚动时都必须进行相同的偏移量计算。
希望这能有所帮助。
https://stackoverflow.com/questions/15391808
复制相似问题