2011-12-10 103 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