简体   繁体   中英

Javascript: how can I judge an element is in viewport?

I have a <ul> element. It's CSS overflow property is scroll .
I have several list elements in the list, such that there is a scrollbar.

<ul style="overflow: scroll; height: 100px;">
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   ...
   <li></li> // how can I judge if this element is in the viewport?
</ul>

How can I determine if a specific list item is visible in that list?

Also, if it's not currently visible, what property can I use to make it scroll into view?

PS: No libraries, please (jQuery, MooTools, etc) .

This is a function I just came up with.

I did some testing on the jsFiddle link at the end of this answer, and it seems consistent.


function elementInViewOfParent(elem) {
    var container = elem.parentNode;
    return (container.scrollTop + container.offsetHeight) >= elem.offsetTop &&
           (container.scrollTop - elem.offsetHeight) <= elem.offsetTop;
}



jsFiddle example - Just scroll it wherever you want, and click the button.
It checks for the red LI 's visiblity, in this example.

If you are okay with using jQuery, this will scroll so that elem is visible and at the top.

function scrollTo(elem) {
    var offset = $(elem).offset();
    $(window).scrollTop(offset.top);
}

(You could even animate the scroll: jQuery scroll to element ).

Another solution would be to use <a target="foo"></a> , and the change the URL fragment to scroll to a particular element, but you specifically asked to be able to tell from JavaScript, which this does not allow you to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM