贪吃蛇是一款80后、90后比较熟悉的经典游戏,下面通过简单的JS代码来实现低仿版贪吃蛇效果:随着鼠标的移动,在页面中呈现所有Div块跟随鼠标依次移动,效果如下图所示。
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>习题-仿select下拉框</title> <style> div { width: 20px;height: 20px;background-color: purple;position: absolute; } </style> <script> //此处写代码 </script></head><body> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div></body></html>
参考代码:
window.onload = function () { // getPos函数获取鼠标的坐标 function getPos(ev) { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; return { x: ev.clientX + scrollTop, y: ev.clientY + scrollLeft }; } document.onmousemove = function (ev) { var oEvent = ev || event; var pos = getPos(oEvent); var aDiv = document.getElementsByTagName(‘div‘); //递减循环 for (var i = aDiv.length - 1; i > 0; i--) { aDiv[i].style.left = aDiv[i - 1].offsetLeft + ‘px‘; aDiv[i].style.top = aDiv[i - 1].offsetTop + ‘px‘; } aDiv[0].style.left = pos.x + ‘px‘; aDiv[0].style.top = pos.y + ‘px‘; }}
思考:为什么采用下面递增循环代码就无法达到预期效果?
代码:
// 与参考文档区别部分for (var i = 0; i < aDiv.length - 1; i++) { aDiv[i + 1].style.left = aDiv[i].offsetLeft + ‘px‘; aDiv[i + 1].style.top = aDiv[i].offsetTop + ‘px‘;}
效果:
如果递增循环设计进行修改后,可以实现其它独特效果:(平移连珠直线)
代码:
window.onload = function () { // getPos函数获取鼠标移动时的坐标 function getPos(ev) { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; return { x: ev.clientX + scrollTop, y: ev.clientY + scrollLeft }; } document.onmousemove = function (ev) { var oEvent = ev || event; var pos = getPos(oEvent); var aDiv = document.getElementsByTagName(‘div‘); for (var i = 0; i < aDiv.length - 1; i++) { aDiv[i + 1].style.left = aDiv[i].offsetLeft + 20 + ‘px‘; aDiv[i + 1].style.top = aDiv[i].offsetTop + 20 + ‘px‘; } aDiv[0].style.left = pos.x + ‘px‘; aDiv[0].style.top = pos.y + ‘px‘; }}