首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Offset然后将Offset添加到div

Offset然后将Offset添加到div
EN

Stack Overflow用户
提问于 2013-03-14 01:04:09
回答 1查看 2.5K关注 0票数 2

我的问题是使用.offset()找到浏览器的y位置,有一次我想把类添加到我的div中,我想创建像yourkarma.com这样的东西(看看什么是增强IT的部分)

代码语言:javascript
复制
$(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是一种很便宜的方式。有没有办法让它变得更好?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-14 10:35:02

这并不便宜,但也许更清晰有效的方法是:

代码语言:javascript
复制
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对象,并设置一个标志,这样事件就不会再次触发。它还避免了每次用户滚动时都必须进行相同的偏移量计算。

希望这能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15391808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档