原生JS实现的多个彩色小球跟随鼠标移动动画效果

每个小球移动都有自己的坐标,小球移动的同时,需要进行坐标传递,将第一个坐标依次传递给最后一个坐标,来实现小球跟着移动的效果

实现代码:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>小球运动</title> <style type="text/css"> p { border-radius: 50%; width: 30px; height: 30px; position: absolute; text-align: center; line-height: 30px; color: white; } </style> </head> <body> </body> <script type="text/javascript"> //创建数组存储所有的小球 var balls = []; //创建小球函数 function createballs(){ for (var i = 0;i < 60;i++) { var ball = document.createElement("p"); ball.innerHTML = i + 1; ball.style.backgroundColor = randomColor(); //将创建的小球存储到数组中 document.body.appendChild( ball); //将所有的小球存在数组中 balls.push( ball); } } createballs(); //随机函数 function randomNum(m, n) { return Math.floor(Math.random() * (n - m + 1) + m); } //随机颜色 function randomColor() { return "rgb(" + randomNum(0, 255) + "," + randomNum(0, 255) + "," + randomNum(0, 255) + ")"; } document.onmousemove = function(e){ var eventObj = e || event; for(var i = balls.length - 1;i > 0;i--){ //将小球的下标通过for循环进行传递 balls[i].style.left = balls[i - 1].style.left; balls[i].style.top= balls[i - 1].style.top; } //将第一个小球赋值为最新的事件对象中的坐标 balls[0].style.left = eventObj.clientX + "px"; balls[0].style.top= eventObj.clientY + "px"; } </script> </html>

运行效果:

原生JS实现的多个彩色小球跟随鼠标移动动画效果

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript运动效果与技巧汇总》、《JavaScript动画特效与技巧汇总》、《JavaScript图形绘制技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript数学运算用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ppjsp.html