点击页面爱心效果
1 <!-- 为页面添加爱心特效 --> 2 (function (window, document, undefined) { 3 var hearts = []; 4 window.requestAnimationFrame = (function () { 5 return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || 6 function (callback) { 7 setTimeout(callback, 1000 / 60); 8 } 9 })(); 10 init(); 11 12 function init() { 13 css(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}"); 14 attachEvent(); 15 gameloop(); 16 } 17 18 function gameloop() { 19 for (var i = 0; i < hearts.length; i++) { 20 if (hearts[i].alpha <= 0) { 21 document.body.removeChild(hearts[i].el); 22 hearts.splice(i, 1); 23 continue; 24 } 25 hearts[i].y--; 26 hearts[i].scale += 0.004; 27 hearts[i].alpha -= 0.013; 28 hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color; 29 } 30 requestAnimationFrame(gameloop); 31 } 32 33 function attachEvent() { 34 var old = typeof window.onclick === "function" && window.onclick; 35 window.onclick = function (event) { 36 old && old(); 37 createHeart(event); 38 } 39 } 40 41 function createHeart(event) { 42 var d = document.createElement("div"); 43 d.className = "heart"; 44 hearts.push({ 45 el: d, 46 x: event.clientX - 5, 47 y: event.clientY - 5, 48 scale: 1, 49 alpha: 1, 50 color: randomColor() 51 }); 52 document.body.appendChild(d); 53 } 54 55 function css(css) { 56 var style = document.createElement("style"); 57 style.type = "text/css"; 58 try { 59 style.appendChild(document.createTextNode(css)); 60 } catch (ex) { 61 style.styleSheet.cssText = css; 62 } 63 document.getElementsByTagName('head')[0].appendChild(style); 64 } 65 66 function randomColor() { 67 return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")"; 68 } 69 })(window, document);