Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

html - How to auto scroll to target div with jquery?

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

with a little more action and variables 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');
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...