Files
ClassContent/历届学生/font-end-nine/项目练习/学生项目/张婷/练习/案例自写/0616/案例二.html
2024-09-27 02:06:13 +08:00

66 lines
2.2 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!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: 1000px;
}
.header {
width: 100%;
height: 50px;
margin-top: 120px;
background: red;
}
/* 首先,顶部滑动到一定条件距离,会出现固定的状态。
因此,给这个状态添加一个类名;并通过js动态的在达成条件后加入此状态。 */
.position{
width: 100%;
position: fixed;
left: 0;
top: 0;
/* 顶部距离会受margin-top的影响,因此也要为0 */
margin-top: 0;
}
</style>
</head>
<body>
<div class="header"></div>
</body>
<!-- 首先判断,所谓的顶部header在父元素body上,实际上是没有变动的,变动的距离是父元素body到顶部的距离
因此变动的实际上是父元素。
思路:我们可以先获取body和header这个元素,然后通过判定body的scrollTop(滚动条的垂直位置,向下滑动值随之增大);
当scrollTop>margin-top120时,header和vh小于等于0,因此实现固定,否则就还是原有的header状态。 -->
<script>
function $(className){
return document.querySelector(className)
}
// 实际上,直接 $('.header') $('body')这样,就已经可以获取节点了
// 下面这样是为了简写和方便一点
// 1: 获取节点并赋值
var header = $('.header')
var body = $('body')
// 2: 绑定事件和处理函数
body.onscroll = function(){
// console.log(11);滚动显示11说明事件绑定成功
// document.documentElement.scrollTop包含整个html,我们所能看到的距离顶部的距离
if (document.documentElement.scrollTop >= 120){
// header position实际上就类似于公共css里面的类名直接追加到html上的书写方式
header.className = "header position"
}else{
header.className = "header"
}
}
</script>
</html>