1.实现效果
2.思路分析 搭建好html网页结构
1 2 3 4 5 6 7 8 9 10 11 12 13 <div class ="banner" > <ul class ="imgs" > <li class ="current" > <img src ="http://edu-image.nosdn.127.net/330ef6517f7a405b93543f6d7d9b37a7.png?imageView&quality=100" alt ="" > </li > <li > <img src ="http://edu-image.nosdn.127.net/e5772242fee541b09be8640c1b85a522.jpg?imageView&quality=100" alt ="" > </li > <li > <img src ="http://edu-image.nosdn.127.net/789ee7d88161487181586674ef72cf46.png?imageView&quality=100" alt ="" > </li > <li > <img src ="https://oimagec2.ydstatic.com/image?id=8593252374131954365&product=xue" alt ="" > </li > <li > <img src ="http://edu-image.nosdn.127.net/a1a77fe9f40e43edaef2b30d22a0d15e.png?imageView&quality=100" alt ="" > </li > </ul > <div class ="prev arrow" > > </div > <div class ="next arrow" > < </div > </div >
定义了一个div盒子,div盒子包含了一组图片和切换的按钮,通过CSS定位将按钮摆放到正确的位置
div盒子样式
1 2 3 4 5 6 7 8 .banner { width : 944px ; height : 400px ; background-color : #ff5 ; position : relative; margin : 0 auto; }
按钮样式实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 .arrow { width : 40px ; height : 40px ; background-color : rgba (0 , 0 , 0 , 0.3 ); text-align : center; line-height : 40px ; color : #fff ; position : absolute; top : calc (50% - 20px ); }.arrow :hover { cursor : pointer; }.prev { border-radius : 0 20px 20px 0 ; left : 0 ; }.next { border-radius : 20px 0 0 20px ; right : 0 ; }
通过CSS定位将所有图片叠加到一起, 再通过给li标签添加特定的类current
控制透明度, 透明度为0不显示, 透明度为1则显示。默认显示第一张图片
示意图
示例代码
1 <li class ="current" > <img src ="http://edu-image.nosdn.127.net/330ef6517f7a405b93543f6d7d9b37a7.png?imageView&quality=100" alt ="" > </li >
图片样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 .banner >.imgs { height : 100% ; width : 100% ; position : relative; }.banner >.imgs >li { height : 100% ; width : 100% ; position : absolute; top : 0 ; left : 0 ; opacity : 0 ; transition : opacity 1s linear; }.banner >.imgs >li .current { opacity : 1 ; }.banner >.imgs >li >img { height : 100% ; width : 100% ; }
3.图片切换效果实现 切换效果
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 let currentIndex = 0 ;let imgs = document .querySelectorAll (".banner>.imgs>li" );let titles = document .querySelectorAll (".banner>.titles>li" );let prev = document .querySelector (".banner>.prev" );let next = document .querySelector (".banner>.next" );function banner (num=1 ) { imgs[currentIndex].className = "" ; currentIndex += num; if (num === 1 ) { if (currentIndex >= imgs.length ) { currentIndex = 0 ; } }else { if (currentIndex < 0 ) { currentIndex = imgs.length - 1 ; } } imgs[currentIndex].className = "current" ; } bannerTimer = setInterval (banner, 2000 ) prev.onclick = function ( ) { banner (num=1 ); } next.onclick = function ( ) { banner (num=-1 ); }
这样就完成了轮播图的制作