图片轮播

不管前端技术如何日新月异,有的需求总是不变的,比如图片轮播

那么如何实现呢?

biubiu~思路来了!

首先,我们理一下需求:

界面上每次展示一张图片,间隔一段时间候展示下一张图片;

咦,这里我们是不是有点想法,很明显需要用到setTimeout。

还有一个需求就是,鼠标移动到图片的index时,切换到这张图片;

那么如何切换呢?

很简单,隐藏当前图片,停止它参与的动画,并使选择index对应的图片进入。

思路清晰了,我们来构建HTML吧!

1 2 3 4 5
CSS渲染:

.main{
	position: relative;
}
.preview-list ul {
	list-style: none;
	padding: 0px;
	margin: 0px;
}
.preview-list {
	position: relative;
	height: 220px;
	width: 440px;
	overflow: hidden;
	margin-top: 30px;
}
.preview-list img {
	height: 220px;
	width: 440px;
}
.preview-list ul li {
	position: absolute;
	float: left;
	list-style: none;
}
.preview-list ul li.select {
	display: block;
}
.clear {
	overflow: hidden;
	clear: both;
	width: 0px;
	height: 0px;
}
.list-dot {
	text-align: center;
	position: absolute;
	left: 250px;
	bottom: 10px;
}
.list-dot span {
	border-radius: 10px;
	font: normal normal bold 12px/15px "Microsoft YaHei";
	color: #FFF;
	margin-left: 5px;
	padding: 3px 6px 3px 6px;
	background-color: #F90;
	cursor: pointer;
}
.list-dot span.onselect {
	background-color: #F00;
}

接下来,大显身手吧!

$(document).ready(function(){
		var time = "";
        var index = 1;
		showimg(index);
         //鼠标移入移出
         $(".list-dot span").hover(function () {
            clearTimeout(time);
            var icon=$(this).text();
            $(".list-dot span").removeClass("onselect").eq(icon-1).addClass("onselect");
            $(".preview-list li").hide().stop(true,true).eq(icon-1).fadeIn("slow");
         }, function () {
            index=$(this).text()> 4 ? 1 :parseInt($(this).text())+1;
            time = setTimeout("showimg(" + index + ")", 3000);
         });
     });

     function showimg(num) {
         index = num;
         $(".list-dot span").removeClass("onselect").eq(index-1).addClass("onselect");
         $(".preview-list li").hide().stop(true,true).eq(index-1).fadeIn("slow");
         index = index + 1 > 5 ? 1 : index + 1;
         time = setTimeout("showimg(" + index + ")", 3000);
     }

具体参考: http://codepen.io/ClayLing/pen/Wpjwoy

你可能感兴趣的:(前端,图片轮播,JavaScript)