30行 js 代码 可复用的 左右轮播图对象

引入js文件 new一个对象就可以了   浏览器版本   需要支持animation  和Array.from

 1 //imgBox 必须有id
 2 //会占用该部分 z-index 1-3的位置  如有按钮请放在z-index 4上
 3 //imgBox 为包含图片的对象  left对象点击向左 right对象点击向右
 4 function Broadcasting(imgBox, left, right) {
 5     var head = document.getElementsByTagName('head')[0];
 6     var foo = imgBox.children[0].offsetWidth + 'px';
 7     var style = document.createElement('style');
 8     var name = imgBox.id.toString();
 9     this.left = left;
10     this.right = right;
11     style.innerHTML = '@keyframes ' + name + 'moveRight{0%{left:' + foo + ';}100%{left:0;}}@keyframes ' + name + 'moveLeft{0%{left:0;}100%{left:-' + foo + ';}}@keyframes ' + name + 'moveRight2{0%{left:0px;}100%{left:' + foo + ';}}@keyframes ' + name + 'moveLeft2{0%{left:-' + foo + ';}100%{left:0px;}}';
12     head.appendChild(style);
13     var arr = Array.from(imgBox.children);
14     this.left.onclick = function () {
15         arr[0].style.zIndex = 1;
16         arr[arr.length - 1].style.animation = name + 'moveLeft 1s';
17         arr[arr.length - 1].style.zIndex = 2;
18         arr[arr.length - 2].style.animation = name + 'moveRight 1s';
19         arr[arr.length - 2].style.zIndex = 3;
20         var tem = arr.pop();
21         arr.unshift(tem);
22     }
23     this.right.onclick = function () {
24         arr[arr.length - 2].style.zIndex = 1;
25         arr[arr.length - 1].style.animation = name + 'moveRight2 1s';
26         arr[arr.length - 1].style.zIndex = 2;
27         arr[0].style.animation = name + 'moveLeft2 1s';
28         arr[0].style.zIndex = 3;
29         var tem = arr.shift();
30         arr.push(tem);
31     }
32 }
posted @ 2018-02-06 17:29  路人甲-郁金香  阅读(162)  评论(0编辑  收藏  举报