Correction status:qualified
Teacher's comments:
在实际开发中,我们经常需要将页面元素进行运动和拖拽以获取更好的页面效果
1、运动原理:即改变盒子的offsetLeft属性来获得位置的改变,取得一个盒子的运动效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js运动原理</title> <style> .ball1{ width: 100px; height: 100px; background-color: aquamarine; border-radius: 50%; position: absolute; top:50px; left:50px; } </style> </head> <body> <button>动起来</button> <button onclick="reset()">复位</button> <div class="ball1"></div> <script> var btn = document.querySelector('button'); var ball1 = document.getElementsByClassName('ball1')[0]; var timer = null; btn.onclick = function(){ clearInterval(timer); timer = setInterval(function() { if(ball1.offsetLeft < 500){ ball1.style.left = ball1.offsetLeft+5+'px'; }else{ clearInterval(timer); } },100); } function reset() { clearInterval(timer); ball1.style.left = '50px'; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
2、拖拽原理:分三个动作,选中 移动 放下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖拽</title> <style> .ball2{ width: 100px; height: 100px; background-color: aquamarine; border-radius: 50%; position: absolute; top:100px; left:100px; } </style> </head> <body> <div class="ball2"></div> </body> <script> //onmousedown 选中 onmousemove 移动 onmouseup 放下 var ball2 = document.getElementsByClassName('ball2')[0]; //event.clientX 鼠标横轴 event.clientY鼠标纵轴 ball2.onmousedown = function (event) { var x = event.clientX - ball2.offsetLeft; var y = event.clientY - ball2.offsetTop; document.onmousemove = function(event) { ball2.style.left = event.clientX - x +'px'; ball2.style.top = event.clientY - y +'px'; } document.onmouseup = function() { document.onmousemove = null; } } </script> </html>
点击 "运行实例" 按钮查看在线实例