獲取滾動條到頂部的距離javascript
<style type="text/css">
#btn {width:40px; height:40px; position:fixed; right:65px; bottom:10px; display:block; background:url(images/top_bg.png) no-repeat left top;}
#btn:hover {background:url(images/top_bg.png) no-repeat 0 -39px;}
.bg {width:1190px; margin:0 auto;}
.testdiv{width:2000px;height:2787px;background-color: #ccc;margin:0 auto;}
</style>
htmlcss
<a href="" id="btn" title="回到頂部"></a>
$(function(){
$('#btn').click(function(){
$('body,html').animate({scrollTop:0},5000);
});
});
javascript 用定時器控制每30毫秒距離減去50html
window.onload = function(){
var btn = document.getElementById('btn');
var timer = null;
btn.onclick=function(){
timer = setInterval(function(){
var sHeight = document.body.scrollTop || document.documentElement.scrollTop;
document.documentElement.scrollTop = document.body.scrollTop -= 50;
if(sHeight==0){
clearInterval(timer);
}
},30);
}
}
定義一個漸變的速度,讓滾動平滑些java
window.onload = function(){
var btn = document.getElementById('btn');
var timer = null;
btn.onclick=function(){
timer = setInterval(function(){
var sHeight = document.body.scrollTop || document.documentElement.scrollTop;
var ispeed = Math.floor(-sHeight / 5);
document.documentElement.scrollTop = document.body.scrollTop = sHeight+ispeed;
console.log(sHeight-ispeed);
if(sHeight==0){
clearInterval(timer);
}
},30);
}
}
1.滾動條返回頂部的過程當中用戶能夠拖動滾動條阻止返回 2.當超過可視區域高度時纔出現「返回頂部」按鈕jquery
window.onload = function(){
var btn = document.getElementById('btn');
var timer = null;
var iscroll = false;
//獲取可視區域的高度
var cHeight = document.documentElement.clientHeight;
//滾動條活動期間用戶能夠拖動滾輪
window.onscroll =function(){
var sHeight = document.body.scrollTop || document.documentElement.scrollTop;
//超過可視區域告訴時顯示返回頂部按鈕
if(sHeight>=cHeight){
btn.style.display="block";
}else{
btn.style.display="none";
}
if(!iscroll){
clearInterval(timer);
}
iscroll = false;
}
btn.onclick=function(){
timer = setInterval(function(){
var sHeight = document.body.scrollTop || document.documentElement.scrollTop;
var ispeed = Math.ceil(sHeight / 5); //建立速度變量
document.documentElement.scrollTop = document.body.scrollTop = sHeight-ispeed;
console.log(sHeight-ispeed);
iscroll = true;
if(sHeight==0){
clearInterval(timer);
}
},30);
}
}