偏移然后addclass到div

时间:2013-03-13 17:04:09

标签: jquery class action offset

我的问题是使用.offset()找到浏览器的y位置 并且有一次我想在我的div中添加类 我想创建像yourkarma.com这样的东西(看看什么是POWERING 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是一种便宜的方式。 反正有没有做出更好的?

1 个答案:

答案 0 :(得分:1)

这并不便宜,但可能更清晰有效的方式是:

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对象并设置一个标志,以便事件不会再次触发。每次用户滚动时,它也不必进行相同的偏移计算。

希望这有帮助。

相关问题