作为一名前端工程师,手写轮播图应该是最基本掌握的技能,以下是我自己原生js写的轮播,欢迎指点批评:
首先css代码
| 代码如下 | 复制代码 |
|
a{text-decoration:none;color:#3DBBF5;} *{ margin:0; padding:0; } .wrapper{ width:400px; height:300px; margin:100pxauto; } #lunbo{ position:relative; overflow:hidden; } #list{ position:relative; white-space:nowrap; // 这块用行元素模拟,所以才用该属性,块元素可修改这块 } #list span{ display: inline-block; width:400px; height:300px; text-align:center; line-height:300px; font-weight:bold; font-size:100px; color:#fff; } #buttons{ position:absolute; bottom:0; text-align:center; width:100%; height:40px; line-height:40px; } #buttons span{ display: inline-block; width:15px; height:5px; background:#fff; margin:010px; cursor:pointer; transition:all.5s; } #buttons span.on{ height:20px; } .arrow{ position:absolute; top:50%; transform: translateY(-50%); font-size:80px; font-weight:bold; color:#fff; opacity: .3; transition:all.5s; } .wrapper:hover .arrow{ opacity:1; } #prev{ left:10px; } #next{ right:10px; } | |
然后HTML代码
| 代码如下 | 复制代码 |
|
| |
最后js代码
| 代码如下 | 复制代码 |
|
window.onload=function() { varlunBo = document.getElementById("lunbo"); varlist = document.getElementById("list"); varbtn = document.getElementById("buttons").getElementsByTagName('span'); varprev = document.getElementById("prev"); varnext = document.getElementById('next'); varinterval = 3000; vartimer; varindex = 1; varanimated =false; for(vari=0;i btn[i].onclick=function() { if(this.className=='on')//如果是状态按钮直接返回节约资源 { return }; varmyIndex =parseInt(this.getAttribute('index'));//获取按钮的index属性值 varoffset = -400*(myIndex-index);//根据属性值 计算偏移量 animate(offset) //轮播动画 index = myIndex;// 改变索引值 showBtn(); //显示状态按钮 } } functionshowBtn () { for(vari=0;i btn[i].className='' } btn[index-1].className='on' } prev.onclick=function() {//上一页事件 if(animated) {//如果是动画状态 直接返回解决bug return; } if(index==1) { index =btn.length; }else{ index-=1; } animate(400); showBtn(); } next.onclick=function() { if(animated) { return; } if(index==btn.length) { index =1; }else{ index+=1; } animate(-400); showBtn(); } functionanimate(offset) { animated =true;//表示在动画状态 varnewLeft = parseInt(list.style.left) + offset;//计算新的left值 vartime = 400;//设置动画总时间 varinterval = 10;//动画帧时间 varspeed = offset/(time/interval);//每帧运动距离 functiongo () { if((speed>0 && parseInt(list.style.left) list.style.left = parseInt(list.style.left) + speed +'px' setTimeout(go,interval) }else{ animated =false;//动画状态结束 list.style.left = newLeft +'px'//现在的位移 if(parseInt(list.style.left) list.style.left = -400 +'px' }elseif( parseInt(list.style.left)>-400){ list.style.left = -2000 +'px' } } } go(); } functionplay () { timer = setTimeout(function() { next.onclick(); play(); },interval) } play(); functionstop () { clearTimeout(timer); } lunBo.onmouseover=stop; lunBo.onmouseout=play; } | |
以上是所有代码,欢迎指点交流!
原神祈愿模拟器最新版
原神祈愿模拟器手机版是一款完整汉化的趣味原神抽卡模拟小游戏,
宝宝森林美食完整版
宝宝森林美食游戏最新版是一款十分有趣的休闲益智游戏,帮助宝宝
g沙盒仇恨官方英文版(gorebox)
G沙盒仇恨英文原版是一款最近非常火热的沙盒模拟类游戏,在这里
迷你世界测试服最新版2024
迷你世界测试服2021最新版,即迷你世界的先遣服版本,用户能
闪耀暖暖最新版2024
闪耀暖暖手游这是非常好玩的换装手游,游戏内容丰富有趣,游戏环