开发者

Javascript to detect if item no longer visible due to scrolling

I've got a ja开发者_如何学JAVAvascript slideshow at the top of my page. When a slide changes to the next image, I call another function to change the background colour of the page.

The client wants the background colour to stop changing when the slideshow is no longer in view, i.e. when the user has scrolled down the page.

Is there any way to detect if an element is no longer visible due to scrolling?


Test code in jQuery

function test() {
    var $elem = $('.test');
    var visibleAtTop = $elem.offset().top + $elem.height() >= $(window).scrollTop();
    var visibleAtBottom = $elem.offset().top <= $(window).scrollTop() + $(window).height();
    if (visibleAtTop && visibleAtBottom) {
        alert('visible');
    } else {
        alert('invisible (at ' + (visibleAtTop ? 'bottom' : 'top') + ')');
    }
}

Full working example at http://jsfiddle.net/9PaQc/1/ (Updated: http://jsfiddle.net/9PaQc/2/ )

P.S. This only checks for vertical scroll. For horizontal, just do the same with top replaced with left, Y -> X and height() -> width()

EDIT

Made it all the way jQuery (to ensure x-browser compatibility) by changing window.scrollY -> $(window).scrollTop()


You can use the jQuery $.scrollTop function, probably from a scroll event handler to script this.


Use the window.pageYOffset to determine scroll amount in window. Use current offset of the object to check if it is in view. Note that these values are mostly browser dependent, so first check if it exists then act on it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜