js部分
1 'use strict'; 2 function RedEnvelope(options){ 3 if(this === window){ 4 return new RedEnvelope(options); 5 } 6 var defaults = { 7 imgWidth:60,//红包的宽度 8 position:'absolute', 9 imgEnvSrc:'../images/game/redEnv/redEnv.png', 10 containerClass:'.redEnv-contain' 11 }; 12 if(!options){ 13 options = defaults; 14 }else{ 15 for (var option in defaults) { 16 if (typeof options[option] === undefined) { 17 options[option] = defaults[option]; 18 } 19 } 20 } 21 this.options = options; 22 this.createEnv(); 23 } 24 RedEnvelope.prototype.createEnv = function(){ 25 var imgEnv = document.createElement('img'); 26 imgEnv.src = this.options.imgEnvSrc; 27 imgEnv.style.width = this.options.imgWidth+'px'; 28 this.evnPosition(imgEnv); 29 } 30 RedEnvelope.prototype.evnPosition = function(img){ 31 var containerWidth = $(this.options.containerClass).width(); 32 var containerHeight = window.screen.height; 33 $(this.options.containerClass).prepend(img); 34 //红包初始的位置 35 img.style.position = this.options.position; 36 var startTop = parseInt(Math.random()*10+(-10)) 37 var startLeft = parseInt(Math.random()*containerWidth); 38 //移动的位置 39 var moveLeft = parseInt(Math.random()*containerWidth+(-30)); 40 var t=parseInt(Math.random() * 1000+1200); 41 this.evnAnimation({'startLeft':startLeft, 'startTop':startTop, 'moveLeft':moveLeft,'moveTop':containerHeight},t); 42 } 43 /*添加元素到主内容上*/ 44 RedEnvelope.prototype.evnAnimation = function (posObject,time){ 45 $(this.options.containerClass).children('img:first').css({'left':posObject.startLeft,'top':posObject.startTop}); 46 $(this.options.containerClass).children('img:first').animate( 47 { 48 'left':posObject.startLeft-posObject.moveLeft, 49 'top':posObject.moveTop 50 }, 51 time, 52 'linear', 53 function(){ 54 $(this).remove(); 55 } 56 ); 57
html部分
<div class="redEnv-contain"> </div> <script> setInterval(RedEnvelope,500); </script>