<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#scroll-box{
width: 30vw;
margin: 0 auto;
padding: .3rem;
background: #efefef;
border: 1px solid #afafaf;
border-radius: .3rem;
white-space: nowrap;
overflow: auto;
scroll-snap-type: x mandatory;
}
.item{
width: 30vw;
line-height: 3rem;
background: #008cc1;
color: #f9f9f9;
text-align: center;
display: inline-block;
scroll-snap-align: center;
}
.item:nth-child(even){background-color: #a1cae4;}
</style>
</head>
<body>
<div id="scroll-box">
<div class="item">A</div>
<div class="item">B</div>
<div class="item">C</div>
<div class="item">D</div>
<div class="item">E</div>
</div>
<script>
var $scroller = document.getElementById('scroll-box');
var itemWidth = $scroller.children[0].offsetWidth;
var counts = [1].concat(Array($scroller.children.length-1).fill(0));
var prev = 0;
$scroller.addEventListener('scroll', e => {
var {scrollLeft} = e.target;
var index = parseInt(scrollLeft/itemWidth);
console.log(index, parseInt(prev/itemWidth))
if(index == parseInt(prev/itemWidth)) return;
counts[index]++;
prev = scrollLeft;
})
</script>
</body>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…