jQuery实现轮播图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
ul {
position: relative;
list-style-type: none;
}
* {
margin: 0;
padding: 0;
}
.box {
height: 450px;
}
.focus {
position: relative;
width: 750px;
height: 450px;
background-color: cornflowerblue;
margin: 0 auto;
}
li {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
.circle {
position: absolute;
bottom: 20px;
left: 50%;
}
.circle span {
float: left;
width: 50px;
height: 10px;
background-color: rgb(16, 207, 80);
margin-right: 15px;
}
li.active {
opacity: 1;
}
span.active {
background-color: rgb(238, 110, 5);
}
</style>
<body>
<div class="box">
<div class="focus">
<ul>
<!-- <li><img src="./banner/banner4.jpg" alt=""></li>
<li><img src="./banner/banner5.jpg" alt=""></li>
<li><img src="./banner/banner6.jpg" alt=""></li>
<li><img src="./banner/banner7.jpg" alt=""></li> -->
</ul>
<div class="circle">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
<script src="./jquery.js"></script>
<script src="./template-web.js"></script>
<script type="text/html" id="tem">
{{each res v i}}
<li><img src={{v.src}} alt=""></li>
{{/each}}
</script>
<script>
$(function() {
var timerId = null;
$.ajax({
type: 'get',
url: './banner.json',
success: function(res) {
console.log(res);
var obj = {
res: res
}
var html = template('tem', obj);
$('ul').html(html);
// 第一个li加active类
$('li').eq(0).addClass('active');
$('span').eq(0).addClass('active');
$('.box').css('background', res[0].background)
var n = 0;
timerId = setInterval(auto, 2000);
// 经过span
$('span').mouseenter(function() {
$(this).addClass('active').siblings().removeClass('active');
// 每个span加索引
var indexSpan = $(this).index();
n = indexSpan - 1;
auto();
})
// 鼠标划入清除定时器
$('.box').mouseenter(function() {
clearInterval(timerId);
})
// 鼠标离开 清除定时器
$('.box').mouseleave(function() {
timerId = setInterval(auto, 2000);
})
// 函数
function auto() {
n++;
if (n >= $('li').length) {
n = 0;
}
$('li').eq(n).stop().animate({
opacity: 1
}, 700, 'linear').siblings().stop().animate({
opacity: 0
}, 700, 'linear');
$('span').eq(n).addClass('active').siblings().removeClass('active');
// 背景颜色改变
$('.box').css('background', res[n].background);
}
}
})
})
</script>
</body>
</html>