2011-12-10 102 views
0

我有这段代码可以使页面向上和向下滚动,请告诉我如何在滚动位置而不是向下滚动页面时单击?向下滚动到位置

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

请进一步澄清您的问题。有点不清楚你想要做什么。 – thwd

回答

0

添加一个变量来存储此刻的“顶”滚动位置点击:

var iPosition = null; 

如果“顶”被点击,保存当前的滚动位置:

iPosition = $(window).scrollTop(); 

如果点击“下”,检查是否存储了滚动位置;如果是,移动到这个位置,否则移动文件的末尾:

$('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(); 
}); 

也看到这个jsfiddle