用scrollTop实现固定定位
最新做项目时,遇到了让固定定位的实现,现整理为一个小demo
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
<style>
html,
body {
margin: 0;
}
#app {
width: 500px;
height: 400px;
background-color: burlywood;
overflow: auto;
}
.child1 {
z-index: 1001;
position: absolute;
top: 0;
width: 400px;
height: 200px;
background-color: chartreuse;
}
.child2 {
padding-top: 200px;
width: 400px;
height: 400px;
background-color: rgb(255, 0, 55);
}
style>
head>
<body>
<div id="app">
<div class="child1">222div>
<div class="child2">333div>
div>
<script>
window.onload = function () {
let app = document.getElementById("app").parentNode;
let child1 = document.getElementsByClassName("child1")[0];
app.addEventListener("scroll", function () {
child1.style.top = app.scrollTop + "px";
})
}
script>
body>
html>
效果图如下: