<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#box {
width: 100%;
height: 50px;
background-color: red;
text-align: center;
line-height: 50px;
position: fixed;
top: 0;
display: none;
}
.box1 {
width: 100%;
height: 600px;
background-color: aqua;
}
.box2 {
width: 100%;
height: 700px;
background-color: orange;
}
.box3 {
width: 100%;
height: 800px;
background-color: yellow;
}
.box4 {
width: 100%;
height: 800px;
background-color: green;
}
#btn {
width: 100px;
height: 25px;
position: fixed;
background-color: aliceblue;
border: 1px solid red;
right: 50px;
bottom: 100px;
cursor: pointer;
display: none;
}
</style>
</head>
<body>
<div id="box">
<h1>我是顶部</h1>
</div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<div id="btn">回到顶部</div>
<script>
var box = document.getElementById('box')
var btn = document.getElementById('btn')
fun()
function fun() {
window.onscroll = function () {
var height = document.body.scrollTop || document.documentElement.scrollTop
if (height >= 400) {
box.style.display = 'block'
btn.style.display = 'block'
} else {
box.style.display = 'none'
btn.style.display = 'none'
}
}
}
fn()
function fn() {
btn.onclick = function () {
window.scrollTo({
top: 50,
// behavior:"smooth"
// behavior:"auto"
behavior: "instant"
})
}
}
</script>
</body>
</html>
这段代码是一个简单的网页,包含一个固定在顶部的红色区域和几个不同颜色的盒子。
开始部分是HTML的基本结构和CSS样式的定义。
接下来是页面的内容,包括一个带有id="box"的顶部区域,和几个具有不同类名的盒子。其中,box1、box2、box3和box4分别代表四个颜色不同的盒子。
最后是一个id为"btn"的按钮,用来回到页面顶部。
在JavaScript部分,通过getElementById函数获取到box和btn元素的引用。
fun函数被调用来检测页面的滚动事件。在滚动事件发生时,通过document.body.scrollTop || document.documentElement.scrollTop获取滚动的高度。如果滚动高度大于等于400像素,则显示box和btn;否则隐藏它们。
fn函数被调用来处理按钮的点击事件。当按钮被点击时,通过window.scrollTo函数将页面滚动到指定的位置,这里是顶部位置,通过top: 50来设置。可以通过behavior属性来选择平滑滚动(behavior: "smooth")、自动滚动(behavior: "auto")或立即滚动(behavior: "instant")的效果。
所以,代码实现了一个滚动到页面顶部并在滚动一定距离时显示回到顶部按钮的功能。