原生js实现简单轮播图
本文实例为大家分享了js实现简单轮播图的具体代码,供大家参考,具体内容如下
一、写入网页基本结构
body:
网页的最外部设置一个id为wrap的容器,取代body,这样方便我们做一些初始化
css:
初始化:
包括外边距margin、内边距padding、链接a、图片img、输入框input、列表ul、li、网页html、body一系列初始化
css设置:
根据图片数与图片宽度设置轮播图宽度
二、设置js逻辑
需要完成的功能有:
1、鼠标移入轮播图逐渐出现左右浮动块
2、点击浮动块切换图片
3、点击小圆点切换图片
4、切换图片同时切换小圆点
5、自动播放
6、鼠标移入轮播图自动播放停止、移出恢复自动播放
代码如下:
Document *{ margin:0; padding:0; } a{ text-decoration:none; } ul,li{ list-style:none; } img{ display:block; } input{ outline:none; } html,body{ height:100%; overflow:hidden; } .content{ position:absolute; top:0; left:0; } .banner{ width:600px; height:400px; position:relative; margin:50pxauto; overflow:hidden; } .banner.bannerList{ position:absolute; left:-600px; top:0; width:4800px; height:100%; } .banner.bannerListli{ float:left; width:600px; height:400px; } .banner.bannerListliimg{ height:100%; width:100%; } .banner.left,.banner.right{ position:absolute; top:50%; transform:translateY(-50%); width:30px; height:50px; border:solid2pxgray; font-size:30px; text-align:center; line-height:50px; color:rgb(255,255,255); opacity:0; transition:1000ms; } .banner.left{ left:0px; } .banner.right{ right:0px; } .banner.point{ position:absolute; bottom:30px; left:50%; transform:translateX(-50%); } .banner.pointli{ float:left; width:15px; height:15px; border-radius:50%; background-color:gray; margin:5px; } window.onload=function(){ varbannerLeft=document.querySelector('.banner.left'); varbannerRight=document.querySelector('.banner.right'); varbanner=document.querySelector('.banner') varbannerList=document.querySelector('.banner.bannerList') varliList=document.querySelectorAll('.banner.bannerListli') varpointList=document.querySelectorAll('.banner.pointli') varstart=-600; timer2=setInterval(function(){//设置定时器,自动播放 vara=30; varindex=bannerList.offsetLeft/-600+1; if(bannerList.offsetLeft==-4200){ bannerList.style.left=-600+'px'//无缝操作 index=2; } if(bannerList.offsetLeft==-3600){ index=1; } for(vari=0;i < >