# 鼠标滚动 切换图片

主要使用:

  • document.onwheel

# 事例

const targetImg = document.getElementById('target');
targetImg.onwheel = function(event) {
  consol.log(event.deltaX); // 横向滚动距离
  consol.log(event.deltaY); // 总想滚动距离
}
body.onwheel = function(event) {
  return false; // 鼠标滚动时-禁止页面滚动
  return true; // 鼠标滚动时-允许面滚动(默认)
}
1
2
3
4
5
6
7
8
9

# 效果


# 代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    html, body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    .box {
      width: 100%;
      height: 100%;
      font-size: 30px;
    }
    .box img {
      width: 100%;
    }
  </style>
</head>
<body>
  <div class="box">
    <div id="scrollText">滚动:0</div>
    <img id="target" src="https://cdn.cnbj1.fds.api.mi-img.com/product-images/mi-f2a1-cond8f0c2c2/section-10-item_0.jpg">
    <!-- https://cdn.cnbj1.fds.api.mi-img.com/product-images/mi-f2a1-cond8f0c2c2/section-10-item_39.jpg -->
  </div>

  <script>
    const scale = 30;
    let num = 0;
    const scrollText = document.getElementById('scrollText');
    const targetImg = document.getElementById('target');
    targetImg.onwheel = function(event) {
      // console.log(event.deltaY, Math.round(event.deltaY));
      num += Math.round(event.deltaY);
      let imgNum = Math.round(num/scale);
      if( imgNum < 0 ) {
        imgNum = 0;
        num = 0;
      }
      if( imgNum > 39 ) {
        imgNum = 39;
        num = 39 * scale;
      }
      // console.log(imgNum);
      scrollText.innerHTML = `滚动:${num}, img: ${imgNum}`;
      targetImg.src = `https://cdn.cnbj1.fds.api.mi-img.com/product-images/mi-f2a1-cond8f0c2c2/section-10-item_${imgNum}.jpg`;
      return false;
    }
  </script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
上次更新: 2022-11-29 16:59:20(UTC +8)