Open Lenny-Hu opened 3 years ago
需求 共有100张图,页面只显示10张图,每张图3-5秒后替换为下一轮图片
思路 数组a存放所有数据,数组b存放当前页面中显示的10条数据,数组c为下一轮所用的数据(也可以记住开始和结束下标从数组a中拿),创建一个1秒运行一次的定时器,包含一个计数器,每次+1。
if 计数器%6==0 获取下一轮的数据存到数组c中 为数组c每项生成随机数秒ms else if 计数器 >= 3 && < 6 遍历数组c,找出ms==计数器的,并替换数组b中对应的数据完成切换显示图片
实际的代码
(function () { $(function () { var app = { data: { vm: null }, bindEvent: function () { }, init: function () { } }; app.data.vm = new Vue({ el: '#app-wrap', template: '#tpl-app-content', data: function () { return { tmp: [], list: [], data: [], timer: null, size: 36, start: 0, speed: [8, 12], n: 0 }; }, methods: { //含最大值,含最小值 getRandomIntInclusive: function (min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }, setRandomMs: function () { for (var i = 0; i < this.data.length; i++) { this.data[i].ms = this.getRandomIntInclusive(this.speed[0], this.speed[1]); } }, setTmp: function () { var _this = this; var _start = _this.start + _this.size; var _end = _start + _this.size; if (_end > _this.data.length - 1) { _end = _this.data.length; _this.start = 0 - _this.size; } else { _this.start = _start; } console.log('本次使用的数据下标', _start, _end); _this.tmp = _this.data.slice(_start, _end); }, refreshList: function () { var _this = this; clearInterval( _this.timer); _this.timer = setInterval(function() { var remainder = _this.n % (_this.speed[1] + 1); _this.n++; if (remainder == 0) { console.log('设置随机秒和数据'); _this.setRandomMs(); _this.setTmp(); return false; } if (remainder < _this.speed[0] || remainder > _this.speed[1]) { // 不做任何操作 return false; } console.log('秒', remainder); for (var i = 0; i < _this.tmp.length; i++) { var _c = _this.tmp[i]; if (_c.ms == remainder) { _this.list[i].opacity = 0; console.log('变', _c.title); // _this.$set(_this.list, i, _c); // 使用css过渡实现淡入淡出(单次时间1秒)。以下还可以优化,定时器创建太多 (function (i, _c) { setTimeout(function () { _this.$set(_this.list, i, _c); }, 1000); })(i, _c); (function (i) { setTimeout(function () { _this.list[i].opacity = 1; }, 1000); })(i); } } }, 1000); } }, created: function () { var pos = -1; for (var i = 0; i < window._data.length; i++) { window._data[i].opacity = 0; window._data[i].i = i; window._data[i].cover = encodeURI(window._data[i].cover); if (window._data[i].id == 'abc') { // 放到数组第12个中间显示 pos = i; } } if (pos >= 0) { var vipIte = window._data.splice(pos, 1); // console.log(vipIte[0], pos); window._data.splice(11, 0, vipIte[0]); } this.data = window._data; console.log('this.data.length', this.data.length); this.list = this.data.slice(this.start, this.size); for (var j = 0; j < this.list.length; j++) { this.list[j].opacity = 1; } }, mounted: function () { this.refreshList(); } }); app.init(); }); })();
需求 共有100张图,页面只显示10张图,每张图3-5秒后替换为下一轮图片
思路 数组a存放所有数据,数组b存放当前页面中显示的10条数据,数组c为下一轮所用的数据(也可以记住开始和结束下标从数组a中拿),创建一个1秒运行一次的定时器,包含一个计数器,每次+1。
实际的代码