jquery +滚动+检查哪些元素可见

时间:2011-09-21 19:21:20

标签: jquery scroll

我想知道jQuery是否可以执行以下操作:

http://jsfiddle.net/AzFJR/2/

- 检查“.main”目前是否可见并动态地将“.active”添加到“nav”中的相应链接?

问候!

编辑:

我使用此Viewport Plugin并使用以下代码进行了解决:

//find what element is in view
var inview = '#' + $('.sectionSelector:in-viewport:first').attr('id'),

//find the corresponding link
$link = $('.mainNav li a').filter('[hash=' + inview + ']');

//check i its already active or not and if not
if ($link.length && !$link.is('.active')) {

    //remove all previous active links and make the current one active
    $('.mainNav li a').removeClass('active');
    $link.addClass('active');    

}

//Start same proccess on every scroll event again
$(window).scroll(function () {
    var inview = '#' + $('.sectionSelector:in-viewport:first').attr('id'),
    $link = $('.mainNav li a').filter('[hash=' + inview + ']');
    if ($link.length && !$link.is('.active')) {
        $('.mainNav li a').removeClass('active');
        $link.addClass('active');    
    }
});

感谢every1的帮助!

2 个答案:

答案 0 :(得分:2)

使用jQuery ELEMENT ‘INVIEW’ EVENT plugin

$('div').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
  if (isInView) {
    // find link and addClass '.active'
  } else {
    // remove the class
  }
});

答案 1 :(得分:0)