如何获取scroll滑动次数?

需要获取到每个 .item 的出现过的次数,要如何弄呐?

<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>
</script>

<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>
阅读 1.9k
1 个回答
<!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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题