<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body,ul,li{
padding: 0;
margin: 0;
}
li{
list-style: none;
}
img{
display: block;
border: none;
}
#bannerBox{
position: relative;
width: 900px;
height: 300px;
border: 1px solid #CECECE;
overflow: hidden;
}
#bannerList{
position: absolute;
height: 300px;
}
#bannerList li{
float: left;
width: 900px;
height: 300px;
}
#bannerList img{
width: 900px;
height: 300px;
}
#btns span{
position: absolute;
top: 50%;
margin-top: -25px;
width: 50px;
height: 50px;
background: #000000;
opacity: .3;
font-size: 40px;
text-align: center;
line-height: 50px;
cursor: pointer;
color: white;
}
#btns .prev{
left: 20px;
}
#btns .next{
right: 20px;
}
#nums{
position: absolute;
right: 20px;
bottom: 20px;
}
#nums li{
float: left;
margin: 10px;
width: 20px;
height: 20px;
border-radius: 50%;
background: white;
color: red;
text-align: center;
line-height: 20px;
cursor: pointer;
}
#nums li:hover,#nums li.hover{
background: red;
color: white;
}
</style>
</head>
<body>
<div id="bannerBox">
<ul id="bannerList">
<li><img src="img/1.jpg"></li>
<li><img src="img/2.jpg"></li>
<li><img src="img/3.jpg"></li>
<li><img src="img/1.jpg"></li>
</ul>
<div id="btns">
<span class="prev"><</span>
<span class="next">></span>
</div>
<ul id="nums">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<script src="startMove.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var oBannerBox = document.getElementById("bannerBox");
var oBannerList = document.getElementById("bannerList");
var aList = oBannerList.children;
var oNum = document.getElementById("nums");
var aNums = oNum.children;
aNums[0].className = "hover";
var perWidth = aList[0].offsetWidth;
var oBtn = document.getElementById("btns");
var oPrev = oBtn.children[0];
var oNext = oBtn.children[1];
oBannerList.style.width = perWidth*aList.length+"px";
var i = 0;
var timer = setInterval(function(){
move();
},3000);
function move(){
i++;
//123 123 临界值
if(i==aList.length){
oBannerList.style.left = 0;
i = 1;
}
//321321 临界值
if(i==-1){
oBannerList.style.left = - perWidth * (aList.length-1)+"px";
i = aList.length - 2;
}
//控制角标,让其和展示图片对应
//先请后加
for(var j = 0; j < aNums.length; j++){
aNums[j].className = "";
}
if(i==aNums.length){
//图片在最后一张(对应第一张)角标的特殊处理
aNums[0].className = "hover";
}else{
aNums[i].className = "hover";
}
startMove(oBannerList,{"left":-perWidth*i});
}
//鼠标移入轮播区域 清除定时器
oBannerBox.onmouseover = function(){
clearInterval(timer);
}
//移出开启
oBannerBox.onmouseout = function(){
timer = setInterval(function(){
move();
},3000);
}
//点击两个按钮
oNext.onclick = function(){
move();
}
oPrev.onclick = function(){
i-=2;//i值变小,抵消move()内部i++
move();
}
//角标 鼠标移入到1,2,3那个数字上,展现对应的图片
for(let j = 0; j < aNums.length; j++){
aNums[j].onmouseover = function(){
i = j-1;
move();
}
}
</script>
</body>
</html>
简单易解的原生JS轮播图
最新推荐文章于 2024-06-17 15:29:34 发布