jQuery焦点轮播(淡入淡出切换)
2018-11-22 本文已影响0人
前端葱叶
很多项目都会用到轮播,轮播的实现也有很多种:
1、用框架(如bootstrap);
2、用插件(如swiper);使用可参考轮播插件swiper的使用;
3、用jQuery等。
很久没写轮播了,这里记录的用jQuery实现的焦点轮播。
和大多数焦点轮播一样,不同的是图片的切换是淡入淡出
的,效果如下;

HTML、CSS代码略过,重点是jQuery逻辑思路的实现:
HTML:
<div class="scroll">
<ul>
<li>
<img src="./img/f-01.jpg" alt="">
</li>
<li>
<img src="./img/f-02.jpg" alt="">
</li>
<li>
<img src="./img/f-03.jpg" alt="">
</li>
<li>
<img src="./img/f-04.jpg" alt="">
</li>
<li>
<img src="./img/f-05.jpg" alt="">
</li>
</ul>
<ol>
<li class="on">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
<span class="arr preArr"></span>
<span class="arr nextArr"></span>
</div>
CSS:
* {
margin: 0;
padding: 0;
}
div {
width: 992px;
height: 420px;
margin: 100px auto 0;
overflow: hidden;
position: relative;
}
li {
list-style: none;
}
ul {
position: relative;
/* overflow: hidden; */
z-index: 1;
}
ul li {
position: absolute;
left: 0;
top: 0;
}
/* 左右箭头 */
div:hover .arr {
display: block;
}
.arr {
width: 40px;
height: 70px;
position: absolute;
top: 175px;
float: left;
background: url('./img/arr.png') no-repeat;
opacity: 0.5;
display: none;
z-index: 3;
}
.preArr {
left: 0;
}
.nextArr {
right: 0;
background-position: -40px 0;
}
/* 数字触发器 */
ol {
position: absolute;
z-index: 2;
right: 10px;
bottom: 10px;
}
ol li {
width: 30px;
height: 20px;
border: 1px solid #ccc;
float: left;
text-align: center;
margin-right: 10px;
cursor: pointer;
}
div ol li.on {
background-color: orange;
}
jQuery逻辑思路:
1、图片切换方法;
2、点击左边按钮切换,当切换到第一张图片时,继续点击切换,显示第五张图片;
3、点击右边边按钮切换,当切换到第五张图片时,继续点击切换,显示第一张图片;
4、鼠标移入到数字触发器切换对应图片;
5、自动切换;
6、鼠标移入轮播范围框时停止自动播放(即取消定时操作),移出框时继续自动播放(即执行定时操作);
jQuery代码:
var index = 0;
var z_index = 100;
var timer = null;
$(function () {
// 二、点击左边按钮切换,当切换到第一张图片时,继续点击切换,显示第五张图片;
$('.preArr').click(function () {
index--;
if (index < 0) {
index = 4;
}
play();
});
// 三、点击右边边按钮切换,当切换到第五张图片时,继续点击切换,显示第一张图片;
$('.nextArr').click(function () {
index++;
if (index > 4) {
index = 0;
}
play();
});
// 五、自动播放setInterval(执行函数,时间)
function playAuto(){
timer = setInterval(function () {
$('.nextArr').click();
}, 2000);
}
playAuto();
// timer = setInterval(function () {
// $('.nextArr').click();
// }, 2000);
// 六、鼠标移入轮播范围框时停止自动播放(即取消定时操作),移出框时继续自动播放(即执行定时操作);
$('.scroll').mousemove(function () {
clearInterval(timer);
}).mouseleave(function(){
// timer=setInterval(function(){
// $('.nextArr').click();
// },2000);
playAuto();
})
// 四、数字触发
$('ol li').mouseover(function () {
index = $(this).index();
play();
})
//步骤一、图片切换方法
function play() {
z_index++;
// 当前图片淡入fadeTo(时间,透明度),透明度0(完全透明)~1(不完全透明)
$('ul li:eq(' + index + ')').css('z-index', z_index).hide().stop().fadeTo(500, 1);
// 播放时,数字触发器会跳转到图片对应的数字
$('ol li:eq(' + index + ')').addClass('on').siblings().removeClass('on');
}
})
学习笔记整理记录,供学习参考,如有错误之处,望指出,共同进步!