只有當頁面被滾動而不是僅僅檢查每1/2秒時檢查滾動位置可能會更好。
我已經把我的想法一個工作演示你想在這裏:http://jsfiddle.net/swpqpv4r/5/
基本上,我們需要看看窗口底部的滾動位置,因爲我們不是滾動的頂部使用document.body.scrollTop + $(win).height()
。通常我們可能會擔心如果窗口被調整大小會發生什麼,但是我們每次都在scroll事件內部計算這個值,所以如果窗口更改大小,它不應該成爲問題。
接下來我們需要知道頁腳的頂部何時在窗口底部滾動。我們可以使用$("#footer").position().top;
來查看它的頂部位置。
希望代碼有足夠的評論來幫助解釋它。如果您有任何問題,請告訴我。
HTML
<header>Top</header>
<br><br><br> <!-- Lots of these for testing -->
<footer id="footer">Bottom</footer>
<a id="btt" href="javascript:{};">Back to top</a>
的JavaScript
$(function(){
//select once and re-use later
var $win = $(window);
var $btt = $("#btt");
var $foot = $("#footer");
var bttDisplay = 500;
var footerHeight = $foot.outerHeight();
var footerTop = $foot.position().top;
function updateScroll() {
var scrollBottom = document.body.scrollTop + $win.height();
if (scrollBottom >= bttDisplay && scrollBottom <= footerTop) {
//show it by setting the bottom position to 0
animateBtt(0);
}else if (scrollBottom >= footerTop) {
//move it up above the footer's top position
animateBtt(footerHeight);
}else {
//hide it by setting the bottom position to the negative value of it's height
animateBtt($btt.height() * -1);
}
}
function animateBtt(pos){
$btt.animate({
"bottom": pos
}, 300);
}
//run initially
updateScroll();
//Create a var to hold the timer
var scrollTimer = null;
$win.on("scroll",function(ev){
//when scrolling, clear the timer
clearTimeout(scrollTimer);
//Now set the timer to run a function after a small delay.
//This prevents the update from happening too many times when you scroll
scrollTimer = setTimeout(updateScroll, 50);
});
//click to scroll back up
$btt.on("click",function(){
$('html, body').animate({scrollTop:0},300);
})
});
CSS
html,body{
margin:0;
padding:0;
}
header, footer{
background: #CCC;
padding: 10px;
}
#btt{
position:fixed;
height: 30px;
width: 100px;
text-align:center;
bottom: -30px;
right:0;
background: #F00;
color: #FFF;
z-index: 1000;
}
更多類似這樣的...解決它,但希望不要做INTERV並且只在滾動更改時更新。 '功能更新(){ \t \t如果($(窗口).scrollTop()==的$(document).height() - $(窗口).height()){ \t \t \t $('# BTT'。)動畫({ \t \t \t \t 「底部」: '120像素' \t \t \t \t},300); ($(window).scrollTop()> 300 && $(window).scrollTop()!= $(document).height() - $(window).height()){else if($(window).scrollTop()> 300 else $(window).scrollTop 。 \t \t \t $( '#BTT')動畫({ \t \t \t \t 「底部」: '60像素' \t \t \t \t},300); \t \t} \t \t其他{ \t \t \t $( '#BTT')。動畫({ \t \t \t \t 「底部」: '-80px' \t \t \t},300); \t \t \t} \t \t} \t的setInterval(更新,500);' – RooksStrife 2015-02-12 00:33:13
你是什麼意思?上面的解決方案將在滾動事件上執行此操作,而不是按照間隔操作。 – 2015-02-12 14:56:27