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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8773405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:00:48  来源:igfitidea点击:

How to auto scroll to target div with jquery?

jqueryhtml

提问by Rolando

If I have a structure like:

如果我有这样的结构:

<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>

Say I continue this pattern until item5... and I wanted to make it so that when the page loads, it would search for the div with itemname "Item5", and scroll to it so that it is visible. Assume that the listofstuffdiv is sized small such that only 3 anitems are shown at any given time, but since overflow:auto exists, user can scroll.

假设我继续这个模式直到 item5... 我想让它在页面加载时,它会搜索 itemname 为“Item5”的 div,然后滚动到它以便它可见。假设 listofstuffdiv 的大小很小,以便在任何给定时间只显示 3 个 anitem,但由于存在 overflow:auto,用户可以滚动。

I want to make it so that jquery can scroll to the item it found so it is visible without the user having to scroll down to item5;.

我想让 jquery 可以滚动到它找到的项目,这样用户就可以看到它,而无需用户向下滚动到 item5;。

回答by

See this fiddle: http://jsfiddle.net/pixelass/uaewc/2/

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

You don't need the scrollTo plugin for this..

为此,您不需要 scrollTo 插件。

jQuery

jQuery

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

$('#listofstuff').animate({scrollTop: scrollAmount},1000);
});

CSS

CSS

.anitem {
height:100px;
}

#listofstuff {

height:300px;
    overflow:auto;
}


with a little more action and variableshttp://jsfiddle.net/pixelass/uaewc/5/

更多的动作和变量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');
    });
});

回答by Julien Lafont

You can use a plugin like ScrollTo

您可以使用像ScrollTo这样的插件

And call $.scrollTowith a selector when the page is loaded :

$.scrollTo在页面加载时使用选择器调用:

$(document).ready(function() {
    $.scrollTo( $('#listofstuff .aniItem:eq(4)'), 500); // index start with 0
});