向下滚动到位置

scroll down to position

本文关键字:位置 滚动      更新时间:2023-09-26

我有这个代码使页面上下滚动,请告诉我如何使它回到滚动位置,而不是当我点击下页?

<a href="javascript://" id="toDown">Down</a>
<a href="javascript://" id="toTop">Top</a>
<script type="text/javascript">
jQuery.noConflict();
$(window).scroll(function(){
    if($(window).scrollTop() > "0"){
        $('#toTop').fadeIn();
        $('#toDown').hide();
    }else if($(window).scrollTop() == "0"){
        $('#toTop').fadeOut();
        $('#toDown').fadeIn();
    }
});
$('#toTop').click(function(){
    $('html, body').animate({scrollTop:0}, 0);
    $('#toDown').fadeIn();
});
$('#toDown').click(function(){
    $('html, body').animate({$('body').height()}, 0);
    $('#toDown').fadeOut();
});
</script>

添加一个变量来存储点击" top "时的滚动位置:

var iPosition = null;

如果'top'被点击,保存当前滚动位置:

iPosition = $(window).scrollTop();

如果点击了'down',检查滚动位置是否已经存储;如果是,则移动到该位置,否则移动文档末尾:

$('html, body').animate({scrollTop: (iPosition === null ? $('body').height() : iPosition)}, 0);

完整的源代码:

var iPosition = null;                              // new
jQuery.noConflict();
$(window).scroll(function(){
    if($(window).scrollTop() > "0"){
        $('#toTop').fadeIn();
        $('#toDown').hide();
    }else if($(window).scrollTop() == "0"){
        $('#toTop').fadeOut();
        $('#toDown').fadeIn();
    }
});
$('#toTop').click(function(){
    iPosition = $(window).scrollTop();             // new
    $('html, body').animate({scrollTop:0}, 0);
    $('#toDown').fadeIn();
});
$('#toDown').click(function(){
    $('html, body').animate({scrollTop: (iPosition === null ? $('body').height() : iPosition)}, 0);   // changed
    $('#toDown').fadeOut();
});