转盘抽奖组件
2020-07-24 本文已影响0人
zhulichao
- 使用基于组件的开发模式,开发一个转盘抽奖组件,要求组件功能有:①可以设置旋转圈数②组件可复用③其它自行设计。设计对应的dom,css及js代码,最多可使用jQuery和zepto辅助。
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>简单转盘效果</title> <style> #RotateDiv, #RotateDiv2 { width: 50px; height: 50px; color: #fff; text-align: center; line-height: 50px; background: #444; position: relative; margin: 20px; /* 指针效果 */ border-radius: 50px 0 50px 50px; } </style> </head> <body> <p>简单转盘:</p> <p> <button id="RotateBtn">开始抽奖</button> </p> <div id="RotateDiv"></div> <p>默认转动:</p> <p> <button id="RotateBtn2">开始抽奖2</button> </p> <div id="RotateDiv2"></div> <script type="text/javascript"> window.iRotate = (function(w, d){ function R(obj, json){ this.obj = (typeof obj === 'object') ? obj : d.querySelector(obj); this.startTime = Date.now(); this.timer = null; this.rotate(json); }; R.prototype = { rotate: function(json) { var self = this; var times = json['time'] || 1000; clearInterval(self.timer); self.timer = setInterval(function() { var changeTime = Date.now(); // 当前消耗时间 var timing = Math.min(times, changeTime - self.startTime); var tweenFun = Tween[json['easing'] || 'easeOut']; // 根据当前时间计算转动角度 var value = tweenFun( timing, +json['start'] || 0, json['end'] - (+json['start'] || 0), times ); self.obj.style['transform'] = 'rotate(' + value%360 + 'deg)'; self.obj.style['-webkit-transform'] = 'rotate(' + value%360 + 'deg)'; self.obj.setAttribute('data-rotate', value%360); // 停止旋转 if(timing == times){ clearInterval(self.timer); json.callback && json.callback.call(self.obj); } }, 10) }, stop: function(fn) { clearInterval(this.timer); fn && fn.call(this.obj); } }; return R; })(window, document); var Tween = { // 匀速转动 linear: function (t, b, c, d){ return c*t/d + b; }, // 逐渐变慢 easeOut: function(t, b, c, d){ return -c *(t/=d)*(t-2) + b; } }; (function(){ // 点击转动 var off = true; RotateBtn.onclick = function(){ if(!off) return; // 判断是否在旋转 off = false; new iRotate('#RotateDiv', { end: 45 + 1800, time: 5000, callback : function(){ // 回调函数 this.innerHTML = this.getAttribute('data-rotate'); off = true; } }); } //默认转动 var r = null; var off2 = true; function rotate2(){ // 递归持续旋转 r = new iRotate('#RotateDiv2', { start: 0, end: 360, time: 1000, easing: 'linear', callback: function(){ rotate2(); } }); } rotate2(); RotateBtn2.onclick = function(){ if(!off2) return; // 判断是否在旋转 off2 = false; r.stop(); // 停止之前的旋转 new iRotate('#RotateDiv2', { start: RotateDiv2.getAttribute('data-rotate'), // 如果不加这个会从0角度开始旋转,有抖动 end: 65 + 1800, time: 5000, callback: function(){ // 回调函数 this.innerHTML = this.getAttribute('data-rotate'); off2 = true; } }); } })(); </script> </body> </html>