运行效果展示
JS实现元素碎片化消失特效
设计思路
-
获取要消失元素的位置、宽高和背景
-
生成碎片覆盖要消失的模块,同时将要消失元素的透明度设为0
-
给碎片设置随机大小、透明度和运动方向
-
碎片运动的同时,透明度降低,为0时清除碎片
-
碎片全部消失后,元素被清除
代码展示
function minbox(i,j,width,height,bg) {
var minbox = document.createElement("div")
minbox.style.width = '20px' //消失碎片初始大小为直径20px的圆形
minbox.style.height = '20px'
minbox.style.borderRadius = '50%'
minbox.style.position = 'absolute'
minbox.style.top = i + 'px'
minbox.style.left = j + 'px'
minbox.style.background = bg //碎片背景对应图片背景
minbox.style.backgroundSize = width + ' ' + height
minbox.style.backgroundPosition = -j + 'px ' + -i + 'px'
minbox.style.overflow = 'hidden;'
minbox.style.transform = 'scale(' + Math.random()*3 + ')' //随机缩放
minbox.style.opacity = parseInt(Math.random()*10)/10; //随机透明度
document.getElementById('bg').appendChild(minbox);
//生成随机运动方向
var h = Math.random()*10 - 5;
var l = Math.random()*10 - 5;
var timer = setInterval(function() {
minbox.style.left = parseInt(minbox.style.left) + l + 'px';
minbox.style.top = parseInt(minbox.style.top) + h + 'px';
minbox.style.opacity = minbox.style.opacity - 0.05 //每移动一次,透明度降低0.05
if(minbox.style.opacity <= 0) { //完全透明后,碎片被清除
clearInterval(timer);
minbox.parentNode.removeChild(minbox)
}
},30)
}
window.onload = function() {
var bg = document.getElementById('bg')
bg.addEventListener('click',function(e){
var img = e.target; //获取被点击元素
let left = img.offsetLeft //获取元素位置
let top = img.offsetTop
let height = getComputedStyle(img).height //获取元素大小
let width = getComputedStyle(img).width
var background = getComputedStyle(img).background //获取元素背景
let h = top + parseInt(height)
let w = left + parseInt(width)
img.style.opacity = 0
for(i = top; i < h; i = i + 20) {
for(j = left; j < w; j = j + 20) {
minbox(i,j,width,height,background)
}
}
setTimeout(function() {
bg.removeChild(img)
},600)
})
}