JavaScript实现一串div跟随鼠标移动效果
上一篇博文我们说到了利用JavaScript实现div块跟随鼠标移动的效果。现在来讲一个进阶版,实现一串div跟随鼠标移动效果,鼠标幻影效果。如图:
在这里插入图片描述
HTML代码:
<divclass="box"></div><divclass="box"></div><divclass="box"></div><divclass="box"></div><divclass="box"></div><divclass="box"></div><divclass="box"></div><divclass="box"></div><divclass="box"></div><divclass="box"></div>
CSS代码:
* { margin: 0; padding: 0; } .box { width: 10px; height: 10px; /* background: green; */ position: absolute; } .box:nth-of-type(n) { background: red; } .box:nth-of-type(2n) { background: green; } .box:nth-of-type(3n) { background: yellow; } .box:nth-of-type(4n) { background: blue; } .box:nth-of-type(5n) { background: pink; } .box:nth-of-type(6n) { background: orange; } .box:nth-of-type(7n) { background: skyblue; } .box:nth-of-type(8n) { background: hotpink; } .box:nth-of-type(9n) { background: purple; } .box:nth-of-type(10n) { background: gold; }
JS代码:
var aBox = document.getElementsByClassName("box"); var timer; document.onmousemove = function (ev) { clearInterval(timer); var ev = ev || window.event; // 设置一个div块跟随鼠标移动 aBox[0].style.top = ev.pageY + "px"; aBox[0].style.left = ev.pageX + "px"; for (var i = aBox.length - 1; i > 0; i--) { aBox[i].style.top = aBox[i - 1].style.top; aBox[i].style.left = aBox[i - 1].style.left; } // 设置定时器 每隔一段时间让后面一个div覆盖前面一个div的位置 timer=setInterval(function () { for (var i = aBox.length - 1; i > 0; i--) { aBox[i].style.top = aBox[i - 1].style.top; aBox[i].style.left = aBox[i - 1].style.left; } },10) }