如何使用jquery自动滚动到目标div?

Rol*_*ndo 6 html jquery

如果我有一个像这样的结构:

<div id="listofstuff">
<div class="anitem">
   <span class="itemname">Item1</span>
   <span class="itemdescruption">AboutItem1</span>
</div>
<div class="anitem">
   <span class="itemname">Item2</span>
   <span class="itemdescruption">AboutItem2</span>
</div>
<div class="anitem">
   <span class="itemname">Item3</span>
   <span class="itemdescruption">AboutItem3</span>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)

假设我继续这个模式直到第5项...我想要这样做,以便在页面加载时,它将搜索带有itemname"Item5"的div,并滚动到它以使其可见.假设listofstuffdiv的大小很小,因此在任何给定时间只显示3个anitems,但由于overflow:auto存在,用户可以滚动.

我想这样做,以便jquery可以滚动到它找到的项目,因此它是可见的,而无需用户向下滚动到item5;.

小智 10

看到这个小提琴:http: //jsfiddle.net/pixelass/uaewc/2/

你不需要这个scrollTo插件..

jQuery的

$(document).ready(function(){
    lastElementTop = $('#listofstuff .anitem:last-child').position().top ;
    scrollAmount = lastElementTop - 200 ;

$('#listofstuff').animate({scrollTop: scrollAmount},1000);
});
Run Code Online (Sandbox Code Playgroud)

CSS

.anitem {
height:100px;
}

#listofstuff {

height:300px;
    overflow:auto;
}
Run Code Online (Sandbox Code Playgroud)

更多动作和变量 http://jsfiddle.net/pixelass/uaewc/5/


$(document).ready(function() {
    var wrapper = $('#listofstuff'),
    element = wrapper.find('.anitem'),
    lastElement = wrapper.find('.anitem:last-child'),
    lastElementTop = lastElement.position().top,
    elementsHeight = element.outerHeight(),
    scrollAmount = lastElementTop - 2 * elementsHeight;

    $('#listofstuff').animate({
        scrollTop: scrollAmount
    }, 1000, function() {
        lastElement.addClass('current-last');
    });
});
Run Code Online (Sandbox Code Playgroud)