div元素的运动与控制

tech2024-07-22  58

div元素的运动与控制

有一个块级元素,通过按钮控制其运动:

实现功能题1:通过按钮控制其每秒向右侧增加50px宽度,左边不动。当宽度为500px时不再增加实现功能题2:“开始”、“结束”两个按钮。点击“开始”按钮后,方块左边不动,每隔1秒向右侧增加50px宽度。点击“结束”按钮后停止运动实现功能题3:开始”按钮。方块在运动时的长宽均保持为100px,点击“开始”,每隔1秒整体向右移动50px。实现功能题4:“开始”按钮。方块在运动时的长宽均保持为100px,点击“开始”,实现向右加速运动。有加速效果即可实现功能题5:“开始”按钮。方块在运动时的长宽均保持为100px,点击“开始”,实现折返跑(左右来回匀速运动)

写在同一个HTML页面上,分别实现功能时,刷新页面再点击按钮

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>元素的运动与控制</title> <style type="text/css"> *{ margin: 0; padding: 0; } #div1 { height: 100px; width: 100px; background: green; position: relative; left:0px; } button{ width: 150px; height: 50px; border-radius: 10px; font-size: 20px; margin: 11px; background-color:#666666 ; color: #ff6666; } </style> </head> <body> <button id=but1>题1-开始</button> <button id=but2>题2-开始2</button> <button id=but22>题2-结束2</button> <button id=but3>题3-开始3</button> <button id=but4>题4-开始4</button> <button id=but5>题5-开始5</button> <div id="div1"> </div> <script type="text/javascript"> var btn1=document.getElementById("but1"); btn1.onclick = function () { var div = document.getElementById("div1"); setInterval(function () { if (div.offsetWidth <= 500) { div.style.width = div.offsetWidth + 100 + "px"; } }, 1000); } var btn2_1=document.getElementById("but2"); var timestatic=true; btn2_1.onclick = function () { var div2 = document.getElementById("div1"); timestatic=true; var interval=setInterval(function () { if (div2.offsetWidth <= 2500&&timestatic) { div2.style.width = div2.offsetWidth + 50 + "px"; } else clearInterval(interval); }, 1000); } var btn2_2=document.getElementById("but22"); btn2_2.onclick = function(){ timestatic=false; } var btn3=document.getElementById("but3"); btn3.onclick = function () { var div3 = document.getElementById("div1"); setInterval(function () { if (div3.offsetLeft <= 500) { div3.style.left = div3.offsetLeft + 50 + "px"; } }, 1000); } var btn4=document.getElementById("but4"); btn4.onclick = function () { var div4 = document.getElementById("div1"); let speed= 50; timer= setInterval(function () { speed*=1.05; div4.style.left = div4.offsetLeft + speed + "px"; }, 1000); } var btn5=document.getElementById("but5"); btn5.onclick = function () { var div5 = document.getElementById("div1"); let speed = 50; let max_left = 500; let min_left = 0; timer= setInterval(function () { div5.style.left = div5.offsetLeft + speed + "px"; if(div5.offsetLeft === max_left||div5.offsetLeft === min_left){ speed *=-1; } }, 50); } </script> </body> </html>
最新回复(0)