如果我有这样的结构:
<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>
假设我继续这个模式直到第5项…我想要这样做,以便当页面加载时,它将搜索具有itemname“Item5”的div,并滚动到它以使其可见.假设listofstuffdiv的大小很小,因此在任何给定时间只显示3个anitems,但由于overflow:auto存在,用户可以滚动.
我想这样做,以便jquery可以滚动到它找到的项目,因此它是可见的,而无需用户向下滚动到item5;.
解决方法
看到这个小提琴:
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); });
CSS
.anitem { height:100px; } #listofstuff { height:300px; overflow:auto; }
用更多的动作和变量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'); }); });