js 轮播图(使用class实现)

纯属无聊,还花了一晚上时间o(╥﹏╥)o

1. js部分的代码

/*** 判断对象是否为DOM元素* @param {Object} obj* @returns*/
const isDOM = (obj) => (typeof HTMLElement === 'object')? obj instanceof HTMLElement: obj && typeof obj === 'object' &&(obj.nodeType === 1 || obj.nodeType === 9) &&typeof obj.nodeName === 'string'const createDom = (className = '', tag = 'div') => {const ele = document.createElement(tag)ele.className = classNamereturn ele
}// 返回0-num之间的数
const getRandomInt = (num) => Math.floor(Math.random() * num)
// eslint-disable-next-line no-unused-vars
const getDom = (selector, all = false) => {return all ? document.querySelectorAll(selector) : document.querySelector(selector)
}
class LoopImages {constructor (container, srcArr, config) {// 默认配置this.config = {loop: true, // 是否循环播放autoPlay: true, // 是否自动播放random: false, // 随机播放arrowAlwaysShow: false,duration: 3000 // 自动播放间隔}// 覆盖默认配置Object.assign(this.config, config)// 初始化容器,如果container为DOM对象则直接赋值,否则根据选择器查找if (isDOM(container)) {this.container = container} else {this.container = document.querySelector(container)}// 如果容器不存在if (!isDOM(this.container)) {throw new Error('未找到容器')}// 循环播放图片的地址数组if (!!srcArr && !(srcArr instanceof Array)) {throw new Error('srcArr 为数组')}this.srcArr = srcArr || []this.length = this.srcArr.length// 当前播放到的位置this.current = 0// 初始化内部的容器this.init()// 自动播放this.config.autoPlay && this.autoPlay()}get _length () {return this.length}get _srcArr () {return this.srcArr}set _srcArr (value) {if (!(this.srcArr instanceof Array)) {throw new Error('srcArr 为数组')}this.srcArr = valuethis.length = this.srcArr.length}get _current () {return this.current}set _current (value) {let errMsgif (isNaN(Number(value))) {errMsg = 'current 必须为数字'}if (errMsg) {throw new Error(errMsg)}this.current = Math.min(this.length - 1, value)this.setCurrent()this.rePlay()}render () {if (this.container && this.container.hasChildNodes()) {return}// 渲染DOMthis.initImageList()this.initCircleBtn()this.initArrowBtn()this.setCurrent()this.addEventListener()this.container && this.container.appendChild(this.loopImgBox)}// 设置当前circleBtn和图片setCurrent () {const that = this;(this.cricleBtnList || []).forEach((btn, index) => {index === that.current ? btn.classList.add('current') : btn.classList.remove('current')});(this.loopImgList || []).forEach((img, index) => {index === that.current ? img.classList.add('current') : img.classList.remove('current')})}init () {if (this.loopImgBox) {return}const loopImgBox = document.createElement('div')loopImgBox.className = 'loop-img-box'this.loopImgBox = loopImgBox}// 初始化next,prev按钮initArrowBtn () {// 生成容器if (this.arrowBtnBox) {return}const arrowBtnBox = createDom('arrow-btn-box')this.arrowBtnBox = arrowBtnBoxconst prev = createDom('arrow-btn arrow-btn-prev')this.prevBtn = prevconst next = createDom('arrow-btn arrow-btn-next')this.nextBtn = nextif (this.config.arrowAlwaysShow) {prev.classList.add('arrow-always-show')next.classList.add('arrow-always-show')}arrowBtnBox.appendChild(prev)arrowBtnBox.appendChild(next)this.loopImgBox && this.loopImgBox.appendChild(arrowBtnBox)}initCircleBtn () {if (this.circleBtnBox) {return}const circleBtnBox = createDom('circle-btn-box')this.circleBtnBox = circleBtnBox// 循环生成小圆点, this.length 为当前图片链接数组的长度this.cricleBtnList = []for (let i = 0; i < this.length; i++) {const circleBtn = createDom('circle-btn circle-btn-' + i)this.cricleBtnList.push(circleBtn)circleBtnBox.appendChild(circleBtn)}this.loopImgBox && this.loopImgBox.appendChild(circleBtnBox)}// 图片数组initImageList () {if (this.loopImgList) {return}const loopImgListBox = createDom('loop-img-list')this.loopImgList = []this.loopImgListBox = loopImgListBoxArray.from(this.srcArr).forEach(src => {// eslint-disable-next-line no-unused-vars// const linkA = createDom('loop-img-link', 'a')// linkA.setAttribute('href', '')const img = createDom('loop-img-item', 'img')img.setAttribute('src', src)this.loopImgList.push(img)loopImgListBox.appendChild(img)})this.loopImgBox && this.loopImgBox.appendChild(loopImgListBox)}// 更新视图update () {}addEventListener () {this.prevBtn && (this.prevBtn.onclick = (e) => {e.stopPropagation()this.prev()})this.nextBtn && (this.nextBtn.onclick = (e) => {e.stopPropagation()this.next()});(this.cricleBtnList || []).forEach((btn, index) => {btn.onclick = () => ((i) => {this._current = i})(index)})}autoPlay () {if (this.config.autoPlay) {// 自动播放this.autoPlayInterval = setInterval(() => {this.config.random ? this.random() : this.next()}, this.config.duration)}}stopAutoPlay () {clearInterval(this.autoPlayInterval)}rePlay () {this.stopAutoPlay()this.autoPlay()}next () {// xia一张const current = this.current + 1if (current === this.length) {if (this.config.loop) {this._current = (current) % this.length}} else {this._current = (current) % this.length}}prev () {// shang一张let current = this.currentif (this.current === 0) {if (this.config.loop) {current = this.lengththis._current = (current - 1) % this.length}} else {this._current = (current - 1) % this.length}}random () {// 随机一张let rand = getRandomInt(this.length)while (rand === this.current) {rand = getRandomInt(this.length)}this._current = rand}
}
module && (module.exports = {LoopImages
})

2. css 部分的样式

文件里的 …/img/prev.png 这张小图标如果觉得不大行的话直接到阿狸图标上找一张代替就行

…/img/prev.png

* {margin: 0;padding: 0;box-sizing: border-box;
}
.loop-img-box {width: 100%;height: 100%;overflow: hidden;position: relative;
}.loop-img-list {width: 100%;height: 100%;position: relative;
}.loop-img-item {display: none;width: 100%;height: 100%;
}.loop-img-item.current {display: block;
}.circle-btn-box {position: absolute;display: flex;justify-content: space-between;width: 46px;bottom: 10px;left: calc(50% - 46px / 2);
}.circle-btn {cursor: pointer;width: 10px;height: 10px;border: 1px solid #afafaf;border-radius: 50%;
}.circle-btn.current {background: #272841;
}.arrow-btn-box {width: 100%;height: 40px;display: flex;justify-content: space-between;top: calc(50% - 20px);position: absolute;
}
.arrow-btn-box:hover .arrow-btn {background-image: url('../img/prev.png');
}.arrow-always-show {background-image: url('../img/prev.png');
}.arrow-btn-prev {cursor: pointer;width: 30px;height: 100%;/*background-image: url('../img/prev.png');*/background-repeat: no-repeat;background-position: center;background-size: cover;
}.arrow-btn-next {cursor: pointer;width: 30px;height: 100%;background-repeat: no-repeat;background-position: center;background-size: cover;transform: rotate(180deg);
}.arrow-btn-next:hover, .arrow-btn-prev:hover {background-image: url('../img/prev.png');
}

3. 使用

<template><div><div class="loop-img-container" ref="loopImg"></div></div>
</template>
<script>
const { LoopImages } = require('@/assets/js/utils')
export default {mounted () {const loopImg = new LoopImages(this.$refs.loopImg, [require('@/assets/logo.png'),require('@/assets/img/prev.png'),require('@/assets/logo.png'),require('@/assets/img/prev.png')], {arrowAlwaysShow: true,})loopImg.render()}
}
</script>
<style scoped>
.loop-img-container {width: 90%;border: 1px solid #1f1f1f;height: 200px;margin: 20px auto;
}
</style>

4. 效果

js 轮播图(使用class实现)相关推荐

  1. JavaScript的案例(数据校验,js轮播图,页面定时弹窗)

    1.数据校验             步骤             1.确定事件(onsubmit)并绑定一个函数             2.书写这个函数,获取数据,并绑定id            ...

  2. php 走马灯轮播,Vue.js轮播图走马灯代码实例(全)

    这个是html, 数据中我用了一个数组来放图片的目录, data() { return { superurl: [ { url: '', img: '../../../../static/image/ ...

  3. JS 轮播图 图片切换(定时器)

    标题JS 轮播图 图片切换(定时器) 这次的轮播图与上次的图片切换相比,仅仅是加上了定时器,使其可以自动切换. 上次的图片切换的链接:https://blog.csdn.net/qq_38318589 ...

  4. JS轮播图(网易云轮播图)

    JS 轮播图 写在前面 最聪明的人是最不愿浪费时间的人.--但丁 实现功能 图片自动切换 鼠标移入停止自动播放,显示按钮 点击按钮,实现前后翻 鼠标移入小圆圈,可以跳转到对应图片 点击左右两侧图片部分 ...

  5. html5移动端轮播图特效,支持移动端的纯js轮播图插件awesome-slider

    awesome-slider是一款支持移动端的纯js轮播图插件.该轮播图插件支持任何HTML标签,可以自定义分页标签和Loading效果,支持在前端框架如react中使用. 使用方法 安装: /* y ...

  6. JS轮播图(点击切换、自动播放、悬停控制)

    JS轮播图 轮播图可以说是网页上十分常见的效果,很多朋友在学习JavaScript后都迫不及待的想写一些好看对的效果出来,那么轮播图就是一个很不错的练手实例.下面就是通过JS写的轮播图效果: 功能介绍 ...

  7. html轮播图循环效果,TremulaJS-跨设备多功能的无限循环js轮播图插件

    TremulaJS是一款非常酷的跨设备多功能的无限循环js轮播图插件.TremulaJS是一个客户端javascript UI组件,它基于贝兹曲线和物理动量效应制作各种效果,可以制作无限循环的图片流, ...

  8. html 图片轮播渐变,js轮播图自动切换和css做页面自动渐变

    js轮播图自动切换和css页面自动渐变 效果如下: 可以去jq官网学习:http://www.jq22.com/ 部分代码如下: *{margin: 0; padding: 0;} p{text-al ...

  9. html 轮播切图,JS轮播图的实现方法

    本文实例为大家分享了JS轮播图的实现代码,供大家参考,具体内容如下 需求: 自动轮播,鼠标移入轮播停止.移出继续,小圆点点击切图,左右箭头切图 效果图: 思路 通过编写过渡动画实现轮播效果,图片的出现 ...

  10. 关于js轮播图最后一张图片显示不出来的问题

    今天跟着视频学敲js轮播图,轮播图底部的小圆点是随着图片数量生成的,当时为了测试小圆点生成的数量是否和图片一致,在原来8张图片的基础上多加了一张图片为9张 写完点击底部小圆点使轮播图切换,进行测试.发 ...

最新文章

  1. 【IOS 开发】Object - C 数组使用详解
  2. Python基础教程:使用dict和set
  3. getRealPath(““)与getRealPath(“/“)区别及用法——计算机网络相关学习笔记
  4. 论ORM框架—EntityFrameworkCore
  5. C和指针之字符串编程练习9(在参数1中查找匹配参数2额任意字符)
  6. 深入学习Mybatis框架(二)- 进阶
  7. php 类常量用法,php类常量用法实例分析
  8. android jni 中jnienv,android JNI中JNIEnv類型和jobject類型的解釋
  9. Fiddler抓包 | 竟然有这些骚操作,太神奇了?
  10. Mr.J-- jQuery学习笔记(七)--CSS类操作文本值操作
  11. yum安装ruby_rediscluster安装
  12. iPhone客户端开发笔记(一)
  13. psenet的eval_ctw1500.py解析
  14. XOM版本1.2.5
  15. 服务器无线桥接技巧,两个路由器无线桥接完美教程【图】
  16. Shiro RememberMe 1.2.4 反序列化命令执行漏洞复现 kali docker
  17. 云计算技术架构-云计算四种模式(公有云、私有云、混合云、行业云)
  18. Python实现头条自动发文章,赚点广告费!
  19. CUDA对应的NVIDIA驱动版本对照表
  20. armbian 斐讯n1_斐讯N1安装Armbian

热门文章

  1. linux文件管理器哪个好,4款简单实用的的服务器文件管理工具推荐
  2. 华为oj初级 求解立方根
  3. 基于阿里云ECS弹性云服务器快速搭建Docker环境
  4. CSDN-MarkDown编辑器--- 数学公式
  5. 蓝牙BLE的连接过程,自动连接过程
  6. 基于强化学习的坦克大战python语言实现
  7. 【Python函数的递归】
  8. c++中为什么要用引用?
  9. 2019ccpc省赛榜单
  10. MySQL binlog详解