錨鏈接
優點:
- 簡單快速、沒有兼容性問題
缺點:
- 視覺上不夠直觀,用戶體驗不夠好
用JavaScript製作回到頂部效果
- 當滾動條滾動一定距離的時候,頁面就出現回到頂部的圖標
- 點擊按鈕滾動條滾動到頂部
主要知識點
DOM操作:
- document.getElementById 根據ID獲取標籤元素
- document.documentElement.scrollTop 滾動條的數值,可讀寫
事件運用:
- window.onload 頁面加載完畢後觸發
- onclick 點擊後觸發
- window.onscroll 滾動條滾動時觸發
定時器:
- setInterval() 設置定時器,需傳2個參數
- clearInterval() 關閉定時器,需傳1個參數
用HTML + CSS實現頁面佈局
index.html:
<!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>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>Javascript 返回頂部</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="bg">
<img src="images/bg1.jpg" alt="" />
<img src="images/bg2.jpg" alt="" />
<img src="images/bg3.jpg" alt="" />
<img src="images/bg4.jpg" alt="" />
<img src="images/bg5.jpg" alt="" />
<img src="images/bg6.jpg" alt="" />
<img src="images/bg7.jpg" alt="" />
</div>
<a href="javascript:;" id="btn" title="回到頂部"></a>
</body>
</html>
style.css:
body {
margin-top: 15px;
background-color: #f0f0f0;
}
.bg{
width:1190px;margin:0 auto;
}
.bg img {
width: 100%;
display: block;
margin-bottom: 15px;
-moz-box-shadow:0px 0px 10px #000005; -webkit-box-shadow:0px 0px 10px #000005; box-shadow:0px 0px 10px #000005;
}
#btn {width:40px; height:40px; position:fixed; right:65px; bottom:10px; background:url(images/top_bg.png) no-repeat left top;}
#btn:hover {background:url(images/top_bg.png) no-repeat 0 -39px;}
script.js:
// 頁面加載完畢後觸發
window.onload = function () {
var obtn = document.getElementById('btn');
// 獲取頁面可視區的高度
var clientHeight = document.documentElement.clientHeight;
var timer = null
var isTop = true
// 滾動條滾動時觸發
window.onscroll = function () {
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
}
obtn.onclick = function(){
// 設置定時器
timer = setInterval(function () {
// 獲取滾動條距離頂部的高度
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var ispeed = Math.floor( -osTop / 6 );
document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
isTop = true
console.log(osTop)
if(osTop === 0) {
clearInterval(timer);
}
},30);
}
}