开发者

How to know if some content is in visible area of a div which has a scrollbar? jQuery

I have a table with rows. The table is in a div. The table has a bigger height than the div and therefore the div has a vertical scrollbar and some rows of the table are in the invisible area of the div. All good.

Then through JavaScript I am searching for some text which tells me which row it is in. If that row is not visible, I want to scroll the div to show that row.

How can I determine if that row is in the visible or hidden portion of the div? I can probably get it from doing height calculations but was wonderi开发者_如何学Gong if there's a simpler method.


There is a DOM method called .scrollIntoView() which does exactly what you describe. Here's how to use it:

var tr = document.getElementById("myRow");
tr.scrollIntoView();

The method has an optional alignWithTop argument which not only ensures that the element is visisble, but also places the element is at the top of the scrolling viewport (much like clicking on an anchor, as Shadow Wizard suggests in his comment)


With jQuery, Use the position() function to get the position of the matched row, then set that value in the ScrollTop() function to get to the element.

This is how it's done

var item = $('#test').position().top;
$('button').click(function() {
    $(window).scrollTop(item)
})

Check working example at http://jsfiddle.net/U6tsg/1/

I also created an animated version

var item = $('#test').position().top;
$('button').click(function() {
    $('html, body').animate({
        scrollTop: item
    }, 'slow');
});

Check working example at http://jsfiddle.net/U6tsg/2/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜