<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.main{
position: relative;
width: 450px;
height: 250px;
margin: 20px auto;
overflow: hidden;
}
img {
position: absolute;
width: 450px;
height: 250px;
opacity: 0;
transition: all 1s ease-in-out;
}
img:first-child{
/* z-index: 999; */
opacity: 1;
}
img.on{
opacity: 1;
}
button{
position: absolute;
width: 25px;
height: 50px;
cursor: pointer;
top: 50%;
margin-top: -15px;
opacity: 0;
border: none;
transition: all 1s;
}
button:first-child{
left: 0;
}
button:last-child{
right: 0;
}
button.on{
opacity: 0.5;
}
ul{
position: absolute;
bottom: 10px;
transform: translateX(-50%);
left: 50%;
}
ul li{
float: left;
width: 12px;
height: 12px;
background: #eee;
border-radius: 6px;
list-style: none;
margin-left: 3px;
}
li:first-child{
background: #f00;
}
</style>
</head>
<body>
<div class="main">
<div class="imgs">
<img src="img/0.jpg" alt="">
<img src="img/1.jpg" alt="">
<img src="img/2.jpg" alt="">
<img src="img/3.jpg" alt="">
<img src="img/4.jpg" alt="">
</div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<button><</button>
<button>></button>
</div>
</body>
<script>
var index = 0;
var main = document.getElementsByClassName('main')[0];
var imgs = document.querySelectorAll('img');
var lis = document.querySelectorAll('li');
var leftBut = document.getElementsByTagName('button')[0];
var rightBut = document.getElementsByTagName('button')[1];
var timer = setInterval(run,1000);
//定时
function run(){
index++;
index %= imgs.length;
imgChange();
iconsChange();
}
//图片切换
function imgChange(){
for(var i = 0; i < imgs.length; i++){
imgs[i].style.opacity = '0';
}
imgs[index].style.opacity = '1';
}
//图标切换
function iconsChange(){
for(var i = 0; i < lis.length; i++){
lis[i].style.background = '#eee';
}
lis[index].style.background = '#f00';
}
//鼠标移入移除
main.onmouseover = function(){
leftBut.style.opacity = '0.5';
rightBut.style.opacity = '0.5';
clearInterval(timer);
}
main.onmouseout = function(){
leftBut.style.opacity = '0';
rightBut.style.opacity = '0';
timer = setInterval(run,1000);
}
//图标悬浮
for(var i = 0; i < lis.length; i++){
// lis[i].number = i;
// lis[i].onmouseover = function(){
// index = this.number;
// imgChange();
// iconsChange();
// }
(function(i){
lis[i].onmouseover = function(){
index = i;
imgChange();
iconsChange();
}
})(i);
}
//左右按钮
leftBut.onclick = function(){
index--;
index = index == -1 ? imgs.length-1:index;
imgChange();
iconsChange();
}
rightBut.onclick = function(){
index++;
index %=imgs.length;
imgChange();
iconsChange();
}
</script>
</html>
网友评论