JQuery - 检测元素是否完全在视口中

时间:2013-10-20 20:08:58

标签: jquery plugins viewport

如果元素在视口中完全可见,我正在尝试使用this plugin来执行动画。有点像灯箱效果。它有点反应......但更不是。不确定我是否使用正确的方法。有什么想法吗?

$(window).bind("resize mousewheel scroll scrollStop", function() {
if($(".tailor .content").is(":within-viewport")) {
    $(".tailor").animate({opacity:'1.0'}, 900, 'easeInOutQuart');
}
else {
    $(".tailor").animate({opacity:'0.8'}, 900, 'easeInOutQuart');
}
});

2 个答案:

答案 0 :(得分:4)

这是我用来检测元素何时完全可见然后用它做任何我想做的事情:

// Create jQuery Method
jQuery.fn.isFullyVisible = function(){

var win = $(window);

var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var elemtHeight = this.height();// Get the full height of current element
elemtHeight = Math.round(elemtHeight);// Round it to a whole number

var bounds = this.offset();// Coordinates of current element
bounds.top = bounds.top + elemtHeight;
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

}

//Usage:
$(window).on('scroll', function() {
  if( $('.tailor .content').isFullyVisible() ){
    // do something
  }
});

答案 1 :(得分:0)

没有理由使用插件:-)这应该很容易;

var el = $('.tailor .content');
var $window = $(window);
var isInFrame = false;

$window.on('scroll', function() {
    if((el.offset().top < ($window.scrollTop + $window.height())) && ((el.offset().top + el.heigt()) > $window.scrollTop))
    {
        if(!isInFrame) 
        {
            isInFrame = true;
            el.animate({opacity:'1.0'}, 900, 'easeInOutQuart');
        }
    }
    else
    {

        if(isInFrame) 
        {
            isInFrame = false;
            el.animate({opacity:'0.8'}, 900, 'easeInOutQuart');
        }
    }
});

如果您的元素已经在框架中,您需要跟踪;否则每次滚动时它都会继续重置动画。