这个⿏标点击出现爱⼼的特效经常在别的博客⾥见到,于是我查了度娘后拿来直接⽤上了。虽然不知道原作者是谁,但肯定是个⼤神,只有通过观摩他/她的代码膜拜⼀下啦。直接上代码(解析在代码注释⾥):// ⾃执⾏匿名函数
(function(window, document, undefined) { // 传⼊window,document对象 var hearts = []; // 定义全局变量hearts,值为空数组
// 定义不同浏览器下的requestAnimationFrame函数实现,如果都没有,则⽤setTimeout实现 window.requestAnimationFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
setTimeout(callback, 1000 / 60); } })();
init(); // 执⾏初始化函数 // 定义初始化函数 function init() {
attachEvent(); // 添加点击事件(爱⼼⽣成) gameloop(); // 开始循环移除爱⼼(内含递归) }
// 定义循环函数移除⽣成的爱⼼ function gameloop() {
for(var i = 0; i < hearts.length; i++) { // 循环hearts数组
if(hearts[i].alpha <= 0) { // 如果当前循环的heart对象的透明度为0或⼩于0
document.body.removeChild(hearts[i].el); // 从body对象中移除当前循环的heart对象(通过指针) hearts.splice(i, 1); // 从heart数组中移除当前循环的heart对象(通过下标) continue; // 跳过当前循环,进⼊下⼀个循环 }
hearts[i].y--; // y轴⾃减1
hearts[i].scale += 0.004; // 缩放增加0.004 hearts[i].alpha -= 0.013; // 透明度减少0.013
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].color; }
requestAnimationFrame(gameloop); // 定时器定时执⾏,递归 }
// 定义点击事件函数 function attachEvent() {
var old = typeof window.onclick === \"function\" && window.onclick; window.onclick = function(event) { old && old(); createHeart(event); } }
// 定义创建爱⼼函数
function createHeart(event) {
var d = document.createElement(\"div\"); // 创建⼀个div对象并赋值给变量d d.className = \"heart\"; // 给div对象添加类名 hearts.push({ // 给hearts数组添加heart对象 el: d, // div对象
x: event.clientX - 5, // ⿏标当前位置x轴 - 5 y: event.clientY - 5, // ⿏标当前位置y轴 - 5 scale: 1, // 缩放 alpha: 1, // 透明度
color: randomColor() // 颜⾊(随机颜⾊) });
document.body.appendChild(d); // 添加创建的div对象到body对象 }
// 定义⽣成样式函数 function css(css) {
var style = document.createElement(\"style\"); // 创建⼀个style对象并赋值给变量style style.type = \"text/css\"; // 给style对象添加属性并赋属性值 try {
style.appendChild(document.createTextNode(css)); } catch(ex) {
style.styleSheet.cssText = css; }
document.getElementsByTagName('head')[0].appendChild(style); // 添加创建的style对象到head对象 }
// 定义⽣成随机颜⾊函数 function randomColor() {
css(\".heart{z-index:100000000;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';wid
return \"rgb(\" + (~~(Math.random() * 255)) + \; }
})(window, document);
我就是没有特效,缺特效,⾃⼰写特效,也不⽤别⼈写的特效!嘿嘿,真⾹。
\"能伤害我的,都是我爱的。\"
因篇幅问题不能全部显示,请点此查看更多更全内容