CSS实现返回网页顶部
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>点击返回置顶</title>
<style>
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 10px;
}
#myBtn:hover {
background-color: #555;
}
</style>
</head>
<body>
<!--<button onclick="topFunction()" id="myBtn" title="回顶部">返回顶部</button>-->
<div style="background-color:black;color:white;padding:30px">向下滑动</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">该实例演示了如何实现网页返回顶部效果。</div>
</body>
<script>
var MyDiv =document.getElementById("body");
var bt =document.createElement("button");
bt.id="myBtn";
bt.title="回顶部";
bt.innerHTML = "返回顶部";
bt.onclick ="topFunction()";
pictureDiv.appendChild(bt);
// 当网页向下滑动 20px 出现"返回顶部" 按钮
window.onscroll = function() {scrollFunction()};
function scrollFunction() {console.log(121);
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// 点击按钮,返回顶部
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
</html>