實現返回頁面頂部功能
阿新 • • 發佈:2021-02-18
技術標籤:大二軟設問題集合前端javascriptjquerycsshtml
10.實現返回頁面頂部功能——軟設問題總結
10.1 效果
10.2 程式碼
10.2.1 頁面滾動到某位置返回頂部圖標出現/消失
//js
document.addEventListener('scroll', function() {
if(window.pageOffset >= 500) { //若頁面滾動大於500px 圖示顯示 否則 圖示隱藏
returnTop. style.display = 'block';
}else{
returnTop.style.display = 'none';
}
})
//jQuery
$(window).scroll(function() {
if ($(document).scrollTop() >= 500) { //若頁面滾動大於500px 圖示顯示 否則 圖示隱藏
$(".returnTop").show();
}else{
$(".returnTop").hide();
}
})
10.2.2 點選圖示返回頂部
//js
returnTop. addEventListener('click', function() {
clearInterval(returnTop.timer); //停止上一個timer定時器
returnTop.timer = setInterval(function() { //開始下一個定時器
var t = window.pageYOffset;
if(t > 0){ //使頁面能緩慢滾回頂部
t = window.pageYOffset - 100;
scroll(0, t);
}else{
clearInterval(returnTop.timer) ;
}
}, 10);
})
//jQuery
$(".returnTop").on("click", function() {
$("body, html").stop().animate({ //使用動畫方法,在1000ms內滾回頁面頂部
scrollTop: 0
}, 1000);
})
10.2.3 html和css
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
background-color: darksalmon;
}
.returnTop {
display: none;
position: fixed;
bottom: 150px;
right: 30px;
width: 50px;
height: 50px;
border: 1px solid #333;
border-radius: 8px;
background: url('10.返回頂部/返回頂部.png') no-repeat center center;
background-size: 80%;
cursor: pointer;
}
.one {
height: 600px;
border: #333 2px solid;
}
</style>
<div class="one"></div>
<div class="returnTop"></div>