使用 JS实现元素超过可视区域后固定在头部功能
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
.container {
width: 750px;
margin: 0 auto;
border: 1px solid black;
}
.header {
height: 200px;
}
.content {
height: 300px;
border: 1px solid red;
}
.title {
height: 100px;
text-align: center;
line-height: 100px;
border: 1px solid brown;
}
.fixedWrapper {
height: 100px;
text-align: center;
line-height: 100px;
border: 1px solid yellow;
background-color: brown;
color: white;
}
.footer {
height: 400px;
border: 1px solid blue;
}
.fixed {
position: fixed;
top: 0px;
width: 100%;
max-width: 750px;
}
</style>
<body>
<div class="container">
<div class="header"></div>
<div class="title">
this is title
</div>
<div class="fixedWrapper">
this is fixedWrapper
</div>
<div class="content">
</div>
<div class="footer"></div>
</div>
</body>
<script type="text/javascript">
window.onload = function() {
fixed();
}
//监听滚动事件
window.onscroll = function() {
fixed();
}
function fixed() {
var title = document.getElementsByClassName("title")[0];
//使用JS原生对象,获取元素的Class样式列表
var fixedWrapperClassList = document.getElementsByClassName("fixedWrapper")[0].classList;
var titleClientRect = title.getBoundingClientRect();
if((titleClientRect.top - titleClientRect.height) < 0) {
//固定
if(!fixedWrapperClassList.contains("fixed")) {
fixedWrapperClassList.add("fixed");
}
} else {
//取消固定
if(fixedWrapperClassList.contains("fixed")) {
fixedWrapperClassList.remove("fixed");
}
}
}
</script>
</html>
原理是以div.title为参照物,判断其是否超过可视区域,如果超过,则设置需要div.fixedWrapper固定。
效果如下:
当div.fixedWrapper超过可视区域,固定在头部:
进入可视区域,则取消固定。