开发者

Scroll a list item such that it becomes visible?

I have a list with a bunch of elements. Usually a scrollbar is required to show them all. I add items to the list at runtime. Is there some way to scroll a particular list element such that it is ensured to be visible?:

<ul id='parent'>
  <li>blah<开发者_如何学运维/li>
  ...
  <li id='nthItem'>blah</li>
</ul>

$('#parent').scrollChildToVisible('nthItem');

something like that?

Thanks


To scroll to an element you can use .animate().

Here's an example of a function that scrolls to a jQuery selector (like an ID):

  // This is a function that scrolls to $(selector)
function goToByScroll(selector){
      // Scroll
    $('html,body').animate({
        scrollTop: $(selector).offset().top},
        'slow');
}

You can trigger this function whenever it is necessary. For example right after you've added the element in question:

  // Append item
$("#parent").append("<li id='nthItem'>blah</li>");

  // Scroll to item using function above. 
goToByScroll("#nthItem");

jsFiddle example

Finally, to select an id in jQuery use

$("#nthItem") // correct for an ID

not

$("nthItem") // incorrect
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜