Snake after a 80, 90 are more familiar with the classic game, to achieve low below imitation version of the Snake effect by a simple JS code: As you move the mouse, showing all Div blocks in the page in order to follow the movement of the mouse ,Results as shown below.
<!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>
Reference Code:
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'; } }
Question: Why is an incremental circulation following code will not perform as expected?
Code:
// in Reference document discriminating section 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'; }
effect:
If the incremented loop design changes may be implemented other unique effects :( Lianzhu linear translation)
Code:
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'; } }