57 lines
1.3 KiB
HTML
57 lines
1.3 KiB
HTML
<!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>
|
|
* {
|
|
margin: 0;
|
|
padding: 0;
|
|
}
|
|
body {
|
|
height: 3000px;
|
|
}
|
|
.header {
|
|
width: 100%;
|
|
height: 60px;
|
|
background: #ff0;
|
|
}
|
|
.test {
|
|
width: 100%;
|
|
height: 60px;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="test"></div>
|
|
<div class="header"></div>
|
|
</body>
|
|
<script>
|
|
// 给网页绑定滚动事件
|
|
// 获取滚动条的滚动距离,然后拿滚动距离进行判断 document.documentElement.scrollTop
|
|
// 大于 某个数值 ,给 html 定固定定位,反之不加
|
|
|
|
|
|
var body = $("body"),
|
|
header = $(".header");
|
|
|
|
body.onscroll = () => {
|
|
var offsetTop = document.documentElement.scrollTop;
|
|
console.log("offsetTop: ", offsetTop);
|
|
|
|
if (offsetTop > 60) {
|
|
header.style.position = "fixed"
|
|
header.style.top = "0"
|
|
} else {
|
|
header.style.position = "static"
|
|
}
|
|
}
|
|
|
|
function $(className) {
|
|
return document.querySelector(className)
|
|
}
|
|
|
|
</script>
|
|
</html> |