簡體   English   中英

使用 Java 腳本來回移動元素

[英]Move an element back and forth diagonally using Java Script

我試圖讓我的 div 元素在容器內無限地來回移動。 目標是僅使用 Java 腳本,沒有 CSS 動畫、jQuery 等。

 const container = document.getElementById('container'); const box = document.getElementById('box'); let t = setInterval(move, 1); let pos = 1; function move() { box.style.left = pos + 'px'; box.style.top = pos + 'px'; pos++; if (pos === 150) { clearInterval(t) } }
 #container{ width: 200px; height: 200px; background-color: green; position: relative; } #box{ width: 50px; height: 50px; background-color: red; position: absolute; animation-direction: alternate; }
 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Animation</title> <link href="animation.css" rel="stylesheet"> <script defer src="animation.js"></script> </head> <body> <div id="container"> <div id="box"></div> </div> </body> </html>

所以這里是代碼。 如您所見,我使用 position 相對/絕對值使元素隨 setInterval function 移動。 但是,當我嘗試將其反轉回“它的角落”時,它就行不通了。 老實說,我已經嘗試了一些東西,但我真的找不到不使用任何其他工具的解決方案。 提前致謝。

您需要增加/減少考慮 boolean 變量的值,如下所示:

 const container = document.getElementById('container'); const box = document.getElementById('box'); let t = setInterval(move, 1); let pos = 1; let test = true; function move() { box.style.left = pos + 'px'; box.style.top = pos + 'px'; if (test) pos++; /* move down */ else pos--; /* move up */ /* update the direction when you reach the top or bottom limit*/ if (pos >= 150) test = false else if (pos <= 0) test = true; }
 #container { width: 200px; height: 200px; background-color: green; position: relative; } #box { width: 50px; height: 50px; background-color: red; position: absolute; }
 <div id="container"> <div id="box"></div> </div>

獲得相同結果的替代方法

 const box = document.getElementById('box'); let jump = 1; let pos = 0; window.setInterval(() => { pos = pos + jump; if (pos > 150 || pos < 0) { jump = jump * (-1); } box.style.left = pos + 'px'; box.style.top = pos + 'px'; }, 1);
 #container{ width: 200px; height: 200px; background-color: green; position: relative; } #box{ width: 50px; height: 50px; background-color: red; position: absolute; animation-direction: alternate; }
 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Animation</title> <link href="animation.css" rel="stylesheet"> <script defer src="animation.js"></script> </head> <body> <div id="container"> <div id="box"></div> </div> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM