Scroll to element only if not in view - jQuery

前端 未结 10 1236
醉酒成梦
醉酒成梦 2020-12-13 18:26

I know a variation on this has been asked several times; I\'ve been browsing SO for a while now but either I\'m doing something wrong or I haven\'t found what I need.

<
10条回答
  •  生来不讨喜
    2020-12-13 19:01

    All modern Browsers support this. Visit: http://caniuse.com/#search=scrollIntoView

    function scrollIntoViewIfNeeded(target) { 
        if (target.getBoundingClientRect().bottom > window.innerHeight) {
            target.scrollIntoView(false);
        }
    
        if (target.getBoundingClientRect().top < 0) {
            target.scrollIntoView();
        } 
    }
    

    Update

    The target has to be an Element. If you use jQuery call the function like this:

    scrollIntoViewIfNeeded($(".target")[0]);
    

提交回复
热议问题