html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="container">
<div style="--c : lightcoral;" class="aa">1</div>
<div style="--c: lightseagreen;">2</div>
<div style="--c: lightsalmon;">3</div>
<div style="--c: lightskyblue;">4</div>
<div style="--c: lightcoral;">5</div>
<div style="--c: lightskyblue;">6</div>
<div style="--c: lightcoral;">7</div>
</div>
<div class="point">
</div>
<script>
let containerDiv = document.querySelector(".container")
let pointDiv = document.querySelector(".point")
rect = pointDiv.getBoundingClientRect();
console.log('%O', pointDiv.getBoundingClientRect().top)
let pointTop = 0;
let childrenNodeList = containerDiv.children
containerDiv.addEventListener('scroll', (e) => {
let x = rect.left;
pointTop = rect.top;
for (let i = 0; i < childrenNodeList.length; i++) {
let children = childrenNodeList[i]
if (children.offsetTop - e.target.scrollTop == pointTop) {
console.log("children==>", children)
}
}
})
</script>
</body>
</html>
css代码
* {
margin: 0;
padding: 0;
}
.container {
height: 100vh;
width: 100vw;
overflow-y: auto;
overflow-x: hidden;
scroll-snap-type: y mandatory;
}
.container div {
height: 50px;
width: 10vw;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
background-color: var(--c);
font-size: 20px;
scroll-snap-align: center;
color: #fff;
padding: 100px;
}
.container::before {
position: relative;
top: 0;
left: 50%;
display: block;
content: "";
height: 300px;
width: 10px;
background-color: red;
}
.container::after {
position: relative;
top: 0;
left: 50%;
display: block;
content: "";
height: 300px;
width: 10px;
background-color: red;
}
.point {
position: absolute;
top: 50%;
width: 30%;
height: 2px;
background-color: antiquewhite;
transform: translateY(-50%);
}
.point::after{
position: absolute;
left: 100%;
content: "这里是选择的";
opacity: 0.2;
width: 100px;
height: 100px;
background-color: indianred;
text-align: center;
line-height: 100px;
}