<!DOCTYPE?html?PUBLIC?"-//W3C//DTD?XHTML?1.0?Transitional//EN"?"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html?xmlns="http://www.w3.org/1999/xhtml"?xml:lang="en">
<head>
<title>Javascript?回到頂部效果</title>
<style?rel="stylesheet"?type="text/css">
???#btn?{
???width:40px;
???height:40px;
???position:fixed;
???left:50%;?
???display:none;
???margin-left:610px;
???bottom:30px;?
???background:url(http://img1.sycdn.imooc.com//535e0dc100010e9c00400080.jpg)?no-repeat?left?top;
???}
???#btn:hover?
???{
??????background:url(http://img1.sycdn.imooc.com//535e0dc100010e9c00400080.jpg)?no-repeat?0?-39px;
???}
???.box?
???{
??????width:1190px;?
??????margin:0?auto;?
???}
</style>
<script?type="text/javascript"?>
??window.onload?=?function()
??{
var?obtn?=?document.getElementById('btn');
//獲取可視頁(yè)面的高度
var?clientHeight?=?document.documentElement.clientHeight;
var?timer?=?null;
var?isTop?=?true;
obtn.onclick?=?function()
{
//設(shè)置定時(shí)器
timer?=?setInterval(function()
{
//獲取滾動(dòng)條距離頂部的距離
var?osTop?=?document.documentElement.scrollTop?||?document.body.scrollTop;
if(osTop?>=?clientHeight)
{
obtn.style.display?=?"block";
}
else
{
obtn.style.display?=?"none";
}
if(!isTop)
{
clearInterval(timer);
}
??isTop?=?false;
??var?ispeed?=?Math.floor(-osTop?/?6);
??document.documentElement.scrollTop?=?document.body.scrollTop?=?osTop?+?ispeed;
??isTop?=?true
??console.log(osTop?-?ispeed);
??if(osTop?==?0)
??{
?clearInterval(timer);
??}
},30);
}
?}
</script>
</head>
<body>
<div>
<img?src="http://img1.sycdn.imooc.com//535e0ce800015b7511902787.jpg"?/>
</div>
<a?href="javascript:;"?id="btn"?title="回到頂部"></a>
</body>
</html>
2016-10-28
請(qǐng)認(rèn)真看視頻中的代碼。?
var?osTop?=?document.documentElement.scrollTop?||?document.body.scrollTop;
if(osTop?>=?clientHeight)
{
obtn.style.display?=?"block";
}
else
{
obtn.style.display?=?"none";
}
if(!isTop)
{
clearInterval(timer);
}
??isTop?=?false;
這段代碼應(yīng)該放置到 window.onsroll 的函數(shù)中去,而不是放到obtn.click 事件中。 一切疑問(wèn)請(qǐng)看視頻中的代碼
2015-09-08
是啊 ?你都隱藏了 怎么會(huì)顯示。。。。