56 lines
1.4 KiB
HTML
56 lines
1.4 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>滚动固定</title>
|
|
<style>
|
|
body {
|
|
height: 30000px;
|
|
background: #0000ff5e;
|
|
}
|
|
|
|
.header {
|
|
width: 100%;
|
|
height: 50px;
|
|
background: #ff00003d;
|
|
margin-top: 200px;
|
|
}
|
|
|
|
.fixed {
|
|
position: fixed;
|
|
width: 100%;
|
|
left: 0;
|
|
top: 0;
|
|
margin-top: 0;
|
|
}
|
|
</style>
|
|
</head>
|
|
|
|
<body>
|
|
<div class="header"></div>
|
|
</body>
|
|
<script>
|
|
var header = document.querySelector('.header')
|
|
console.log('header',header);
|
|
document.querySelector('body').onscroll = function(){
|
|
// (定义c即这个元素距离顶部的距离)
|
|
// 要获取当前页面的滚动条纵坐标位置,用:
|
|
// document.documentElement.scrollTop;
|
|
// 而不是:
|
|
// document.body.scrollTop;
|
|
// documentElement 对应的是 html 标签,而 body 对应的是 body 标签。
|
|
|
|
var C = document.documentElement.scrollTop;
|
|
// console.log('c',C);
|
|
if(C >= 200){
|
|
header.className = 'header fixed'
|
|
}else{
|
|
header.className = 'header'
|
|
}
|
|
|
|
}
|
|
</script>
|
|
</html> |