直接开始,HTML CSS部分没备注,JS有
HTML部分
<div style="overflow: hidden;position: relative;left: 0;top: 0;height: 450px;width: 100%">
<div id="slider">
<div></div>
<div></div>
<div></div>
</div>
</div>
css部分
#slider {
width: 300%;
height: 450px;
position: absolute;
overflow: hidden;
}
#slider > div:nth-child(1) {
#sliderModal('http://yxcx.oss-cn-beijing.aliyuncs.com/yxcximg/banner/allline2.jpg');
}
#slider > div:nth-child(2) {
#sliderModal('http://yxcx.oss-cn-beijing.aliyuncs.com/yxcximg/banner/html1.jpg');
}
#slider > div:nth-child(3) {
#sliderModal('http://yxcx.oss-cn-beijing.aliyuncs.com/yxcximg/banner/yizhanshi1.jpg');
}
JS部分
var speed = 15; //设置图片切换速度
var page = 1; //轮播图片
var allPage = $('#slider').children('div').length; //获取轮播图片数
var clientWidth = $(window).width(); //获取浏览器显示宽度
function Mixin() { //所有方法封装方便调用
this.play = function (){ //总开关
setInterval(function () { //2秒换一张图
run.autoPlay();
}, 2000)
};
this.animate = function (val) {
clearInterval(play); //先清除动画
if(val ==0){ //回到第一张图
$('#slider').css({'left': 0 + 'px'})
}else {
var move = (val -1) * -clientWidth; //运动轨迹开始值
var end = val * -clientWidth; //运动轨迹结束值
var play = setInterval(function () { //这给setInterval定义了个名字,好随时停止它
move = move -speed //动画移动速度
$('#slider').css({'left': move || 0 + 'px'}) //开始移动
if (move < end) { //当移动值超过结束值 停止动画
clearInterval(play);
}
}, 5)
}
}
this.autoPlay = function () {
if(page >=allPage){ //超过总图数回到第一张图
page =0;
}
this.animate(page); //插图图几,开始动画
page ++;
};
};
var createslider = function () { //这样写可以不写'new'来调用构造函数,传值也方便
return new Mixin();
};
var run = createslider(); //把函数赋值给RUN才能成功调用play,因为createslider指向本身,
// 而run的constructor指向mixin这个方法,可以用run.__proto__检测
run.play();
console.log(run.__proto__)