【问题标题】:Finding the index of the current element I am scrolling in - Jquery查找我正在滚动的当前元素的索引 - Jquery
【发布时间】:2013-01-25 15:08:16
【问题描述】:

假设我有一些类名为“class”的固定高度自动滚动的 div。我想找到我正在滚动的当前“类”的 div 的索引,如下所示:

var type = -1;
$(window).scroll(function(type_request){
    type = $('.class').index($(this));console.log(type);
});

但是滚动后我没有输出。

【问题讨论】:

  • 很确定你必须绑定到".class",而不是window
  • this 在您的代码中指的是窗口对象。

标签: javascript jquery indexing scroll


【解决方案1】:

看起来你的方法调用被颠倒了。试试这个:

$(window).scroll(function(){
    type = $(this).index();
    console.log(type);
});

编辑:如果您只想滚动带有.class 类的 div,那么您需要专门绑定到该类:

$('.class').scroll(function(){
    type = $(this).index();
    console.log(type);
});

另外,如果您使用的是 jQuery 1.7+,则应该使用 on 而不是 scrollbind('scroll') 的简写):

$('.class').on('scroll', function(){
    type = $(this).index();
    console.log(type);
});

【讨论】:

  • 所以我应该试试 type = $('this .class').index(); ?
  • @undefined jQuery 将this 运算符设置为触发事件的元素,在这种情况下,无论哪个元素被滚动。
  • @jbabey 没错,但在您的第一个代码中,this 是窗口对象。
  • @jbabey 从什么时候开始?这只发生在委托中
  • @Ian 从我记事起。 “当 jQuery 调用处理程序时,this 关键字是对传递事件的元素的引用。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 2022-11-13
  • 2015-10-27
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多