Jquery scrollTop(),或offset(),还是?

时间:2014-04-25 01:21:06

标签: jquery

我有一个带滚动条的div。我有一堆跨度,我想使用scrollTop()或offset()来使我的跨度达到顶部。我可以让scrollTop(像素)工作,但我想知道你是否可以使用ID,或者我使用了错误的函数。

<div id="textOne">
  <span id="s1">I have a paragraph that is full of spans.</span> <span id="s2">I need to      be able to put each span to the top on command.</span> <span id="s3">I don't want them to automatically line up on the left, only on the top</span> <span id="s4">And I need all of the text to be accessable with the scrollbar</span>  <span id="s5">For this demo, I'll make a button to get to s3, but I need to do this in the background, so keep that in mind   please.</span>
</div>

<input type="submit" id="submit" value="SPAN 3">

$(function() {
    $('#submit').click(function() {
        $('#textOne').scrollTop($('#s3'));
    });
});

http://jsfiddle.net/bdenzer/Yu5Jz/1/

2 个答案:

答案 0 :(得分:1)

尝试:

$(function() {
    $('#submit').click(function() {
        $('#textOne').animate({scrollTop: $('#s3').offset().top}, 500);

    });

});

小提琴:http://jsfiddle.net/Yu5Jz/2/

答案 1 :(得分:0)

只需将其添加到您的事件处理程序:

window.location.href = "#s3";

例如:

$(document).on('keyup', function(){
   window.location.href = "#s3";
});