html菜鸟教程轮播图自动播放,原生JS实现轮播图

使用原生JS实现轮播图,仅需短短几行代码,代码如下

let carousel = new Carousel();

carousel.render({

'elem': '#carousel',

'data': [

{

'src': 'http://dancheng.zxdyw.com/U_Image/2016/1201/e/20161201093248_7241.jpg',

'alt': '1',

'title': '1'

},

{

'src': 'http://imgsrc.baidu.com/forum/w=580/sign=585c22802df5e0feee1889096c6134e5/9726a5d6277f9e2faf4b30911f30e924b999f35e.jpg',

'alt': '2',

'title': '2'

},

{

'src': 'http://img4.imgtn.bdimg.com/it/u=1123599174,3662075684&fm=26&gp=0.jpg',

'alt': '3',

'title': '3'

},

],

});

当然,不可能这么简单,这里我引入了自定义的 Carousel 类,是使用原生 JS 写的,全部的代码就不放出来了,只给出实现轮播的核心代码

// nextIndex 下一个 index

change(nextIndex) {

let points = this.points; // 小点点们

let content = this.content; // 主体内容

let items = this.items; // 所有的 item

let maxlen = this.data.length; // 数据个数

let thisIndex = this.getThisIndex(); // 当前显示的 index

// 获取真实的 nextIndex

let realNextIndex = nextIndex;

if (nextIndex > maxlen) {

realNextIndex = 1;

}

if (nextIndex < 1) {

realNextIndex = maxlen;

}

// 获取最小 index 最大 index

let minIndex = Math.min(thisIndex, nextIndex);

let maxIndex = Math.max(thisIndex, nextIndex);

// 获取 index 的差

let subIndex = maxIndex - minIndex;

// 获取 transform 数据的 index

let type = thisIndex > nextIndex;

// 定义起始终止 transform

let startTransform = type ? String(subIndex * this.itemWidth) : '0';

let endTransform = type ? '0' : String(subIndex * this.itemWidth);

// 显示两者及两者之间的 item

for (let i = minIndex; i <= maxIndex; i++) {

items[i].className = ITEMSHOW;

}

// 设置起始 transform

content.style.transform = `translateX(-${startTransform}%)`;

// 给 next 小点点添加 this

points[realNextIndex - 1].className = INDITEMTHIS;

// 去掉之前的小点点的 this

points[thisIndex - 1].className = INDITEM;

// 给 content 添加 transition 和 transform

setTimeout(function () {

content.style.transition = 'transform linear .5s';

content.style.transform = `translateX(-${endTransform}%)`;

}, 5);

// 工作完成后,清除

let timer = setTimeout(function () {

// 清除 content 的 transition 和 transform

content.style.transition = 'transform linear 0s';

content.style.transform = 'translateX(0)';

// 取消掉除 nextItem 之外的其它元素的显示

for (let i = 0; i < items.length; i++) {

items[i].className = ITEM;

}

items[realNextIndex].className = ITEMSHOW;

clearTimeout(timer);

}.bind(this), 500);

}

所有的代码我已经上传到 码云 了,里面有使用方法。

也可以使用百度云下载压缩包(博客园好像不能上传)。

链接:https://pan.baidu.com/s/1u5eNjp0iMDVHAJ3U3e5DYg

提取码:ipvq

(注意,下载之后,文件路径需要修改)

eea2877dff553f73a89dd79cbd2f079b.png

这就是微学网-程序员之家为你提供的"原生JS实现轮播图"希望对你有所帮助.本文来自网络,转载请注明出处:http://www.weixuecn.cn/article/7679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值