<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
body{
height: 1000px;
}
button{
position: fixed;
right: 20px;
bottom: 20px;
display: none;
}
</style>
</head>
<body>
<div id="box">
<button type="button">回到顶部</button>
</div>
<script type="text/javascript">
var btn = document.querySelector("button");
// 回到顶部
btn.onclick = function(){
var height = document.documentElement || document.body;
height.scrollTop = 0;
}
// 滚动事件
window.onscroll = function(){
// 滚动高度
var height = document.documentElement.scrollTop || document.body.scrollTop;
// 滚动高度大于500显示按钮,否则隐藏
if(height>=500){
btn.style.display = "block";
}else{
btn.style.display = "none";
}
}
</script>
</body>
</html>
js:一键置顶(代码)
最新推荐文章于 2024-03-20 14:42:57 发布