本文实例为大家分享了javascript实现滚轮轮播图片的具体代码,供大家参考,具体内容如下
效果图如下,只能用滚轮移动到头部和尾部
思路:
根据需要展示的图片数量(view-count)与slide-container中存放的图片数量设置ul的长度,然后设置每个li的均等宽度。
每次滚轮滚动ul移动一个li的距离
HTML:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
< div class = "slide-container" view-count = "4" > < ul > < li > < img src = "images/women/15444293310974910.jpg" alt = "" /> </ li > < li > < img src = "images/women/15444293312083674.jpg" alt = "" /> </ li > < li > < img src = "images/women/15444293313734437.jpg" alt = "" /> </ li > < li > < img src = "images/women/15444293315979953.jpg" alt = "" /> </ li > < li > < img src = "images/women/15444293316955485.jpg" alt = "" /> </ li > < li > < img src = "images/women/15444293317767707.jpg" alt = "" /> </ li > </ ul > </ div > |
CSS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
.slide-container { max-width : 1230px ; margin : auto ; overflow : hidden ; } .slide-container ul { transition: all 0.5 s linear; } .slide-container li { float : left ; } .slide-container img { width : 100% ; } |
JS:
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
( function () { let slider = $( '.slide-container' ), li = slider.find( 'li' ), length = li.length, curImgIndex = 0; //当前图片索引 //设置ul宽度和li的宽度 function initSlider() { slider.find( 'ul' ).css({ 'width' : length / slider.attr( 'view-count' ) * 100 + '%' }); li.css({ 'width' : 'calc(' + 100 / length + '% - 10px)' , 'margin' : '0 5px' }); } //统一处理滚轮滚动事件 function wheel(event) { var delta = 0; if (!event) event = window.event; if (event.wheelDelta) { //IE、chrome浏览器使用的是wheelDelta,并且值为“正负120” delta = event.wheelDelta / 120; if (window.opera) //因为IE、chrome等向下滚动是负值,FF是正值,为了处理一致性,在此取反处理 delta = -delta; } else if (event.detail) { //FF浏览器使用的是detail,其值为“正负3” delta = -event.detail / 3; } if (delta) { handle(delta); //阻止事件冒泡重复执行和屏幕向下滚动 event.preventDefault() && event.stopPropagation(); } } //上下滚动时的具体处理函数 function handle(delta) { //滚轮向上滚动 if (delta < 0) { curImgIndex++; } else if (delta > 0) { //向下滚动 curImgIndex--; } move(); } function move() { //到达两端则不移动 if (curImgIndex > li.length - slider.attr( 'view-count' ) || curImgIndex < 0){ if (curImgIndex > 0 ){ curImgIndex--; } else { curImgIndex++; } return false ; } slider.find( 'ul' ).css({ 'transform' : 'translateX( -' + 100 / length * curImgIndex + '% )' }) } initSlider(); //绑定滚轮事件兼容性写法 if (window.addEventListener) slider.get(0).addEventListener( 'DOMMouseScroll' , wheel, false ); slider.get(0).onmousewheel = wheel; }()); |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_37728271/article/details/85935087