js原生之元素跟随鼠标运动
div {
height: 20px;
width: 20px;
background-color: red;
position: absolute;
}
var aDiv = []
// 文档碎片
var cache = document.createDocumentFragment()
for (var i = 1; i <= 20; i++) {
var div = document.createElement("div")
div.innerHTML = i
aDiv.push(div)
cache.appendChild(div)
}
document.body.appendChild(cache)
// document绑定mousemove事件
document.onmousemove = function(e) {
e = e || event;
var mouseX = e.clientX,
mouseY = e.clientY
// 从后往前,一次进一步
for (var i = aDiv.length-1; i > 0; i--) {
aDiv[i].style.left = aDiv[i-1].style.left
aDiv[i].style.top = aDiv[i-1].style.top
}
// 第0个赋值未当前鼠标坐标
aDiv[0].style.left = mouseX + "px"
aDiv[0].style.top = mouseY + "px"
}
图例: