Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

如何获取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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<!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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...