用原生js实现轮播
参考自:
https://blog.csdn.net/Zhangeq/article/details/84306332
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播</title>
<style>
*{
margin: 0;
padding: 0;
}
.wrap{
margin-top: 100px;
margin-left: 200px;
width: 1030px;
height: 530px;
position: relative;
border: 1px solid #000000;
overflow: hidden;
border-shadow:0 5px 54px rgb(0, 0, 0);
}
.broadcast
{
width: 1000px;
height: 500px;
position: relative;
overflow: hidden;
margin: 15px;
}
.broadcast ul{
left: 0;
top: 0;
padding: 0;
list-style: none;
width: 400%;/*宽度为原来宽度的4倍*/
height: 100%;
}
.broadcast li{
left: 0;
float: left;
list-style: none;
}
.broadcast img{
width:1000px;
height: 500px;
}
.broadcast ol{
position: absolute;
right: 30px;
bottom: 30px;
}
.broadcast ol li{
position: relative;
float: left;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: rgba(155,155,155,45);
color: #fff;
text-align: center;
margin-right: 15px;
cursor: pointer;
line-height: 20px;
}
.broadcast ol li.first-li{
/*background-color: rgba(248,248,248,0.45);*/
background-color: black;
}
</style>
</head>
<body>
<div class="wrap">
<div class="broadcast" id="broadcast">
<ul id="img_list">
<li> <img src="../css/img/1.jpg" alt="1"></li>
<li> <img src="../css/img/2.jpg" alt="2"></li>
<li> <img src="../css/img/3.jpg" alt="3"></li>
<li> <img src="../css/img/4.jpg" alt="4"></li>
</ul>
<ol id="button_list">
<li class="first-li" id="ollil">1</li>
<li id="olli2">2</li>
<li id="olli3">3</li>
<li id="ollil4">4</li>
</ol>
</div>
</div>
<script>
window.onload=function(){
var broadcast=document.getElementById('broadcast');
img_list=document.getElementById('img_list');
button_list=document.getElementById('button_list').getElementsByTagName('li');
var index=0;
var timer=null;
if (timer){/*先进行初始化操作*/
clearInterval(timer);
timer=null;
}
//自动切换
timer=setInterval(autoPlay,1000);
function autoPlay()
{
index++;
if (index==button_list.length)
{
index=0;
}
imgChange(index);
}
//自动切换函数
function imgChange(buttonIndex){
for (var i=0;i<button_list.length;i++){/*设置所有的button的className属性为空*/
button_list[i].className="";
}
button_list[buttonIndex].className='first-li';/*只设置当前的class属性由有效值*/
img_list.style.marginLeft=-1000*buttonIndex+'px';/*离左边的距离有问题,利用index进行计算*/
}
/*鼠标接触div*/
broadcast.onmouseover=function()
{
clearInterval(timer);/*清除定时器*/
}
/*鼠标离开div*/
broadcast.onmouseout=function(){
timer=setInterval(autoPlay,1000);
}
/*鼠标悬停*/
for (var i=0;i<button_list.length;i++){
button_list[i].id=i;/*给按钮设置id*/
button_list[i].onmouseover=function(){
clearInterval(timer);
imgChange(this.id);/*设置传递给imgChange函数的index*/
}
}
}
</script>
</body>
</html>
轮播效果(来一张我家王源源靓照)