Check if div is viewable in window?

前端 未结 5 1336
庸人自扰
庸人自扰 2021-01-04 05:33

I have a one page site with fixed navigation and using a scroll script, very similar to this: http://www.ivanjevremovic.in.rs/live/temptation/single/orange/index-cycle-slide

5条回答
  •  隐瞒了意图╮
    2021-01-04 06:32

    Here are all the variables you'll need...

    var $myElt       = $('.myElement');      // whatever element you want to check
    var $window      = $(window);            // the window jQuery element
    var myTop        = $myElt.offset().top;  // the top (y) location of your element
    var windowTop    = $window.scrollTop();           // the top of the window
    var windowBottom = windowTop + $window.height();  // the bottom of the window
    

    Then to make sure your element is within the window's range...

    if (myTop > windowTop && myTop < windowBottom) {
        // element is in the window
    } else {
        // element is NOT in the window
        // maybe use this to scroll... 
        // $('html, body').animate({scrollTop: myTop}, 300);
    }
    

    jQuery reference:

    • http://api.jquery.com/offset/
    • http://api.jquery.com/height/
    • http://api.jquery.com/scrollTop/

提交回复
热议问题