移動(dòng) div 是一種網(wǎng)頁元素,可以自動(dòng)在屏幕上移動(dòng)或更改屏幕上的位置。通過調(diào)整左側(cè)和頂部樣式屬性來更改位置。使用 JavaScript 創(chuàng)建移動(dòng) div 是一項(xiàng)相對簡單的任務(wù)。所需要的只是一點(diǎn) HTML、CSS 和 JavaScript 代碼。在本教程中,我們將介紹如何使用 JavaScript 創(chuàng)建移動(dòng) div。
HTML 代碼
我們首先需要的是一些 HTML 代碼。我們將創(chuàng)建一個(gè) id 為
“移動(dòng)Div”。在此 div 內(nèi),我們將放置一些內(nèi)容。此內(nèi)容可以是您的任何內(nèi)容
想要,但對于這個(gè)例子,我們只添加一些文本。
<div id="movingDiv"> This is my moving div! </div>
登錄后復(fù)制
現(xiàn)在我們有了 HTML 代碼,我們需要一些 CSS 代碼。
CSS 代碼
CSS 代碼將使我們的 div 真正移動(dòng)。我們將設(shè)置 div 的位置
到“親戚”。這將允許我們使用 JavaScript 移動(dòng) div。我們還將設(shè)置
div 的寬度和高度。
#movingDiv { position: relative; width: 200px; height: 200px; }
登錄后復(fù)制
現(xiàn)在我們有了 HTML 和 CSS 代碼,我們需要一些 JavaScript 代碼。
JavaScript 代碼
JavaScript 代碼實(shí)際上會(huì)讓我們的 div 移動(dòng)。我們將使用 setInterval 函數(shù)每 1000 毫秒(1 秒)移動(dòng)一次 div。我們還將使用 CSS 屬性“top”和“l(fā)eft”來移動(dòng) div。
var interval = setInterval(function() { var div = document.getElementById("movingDiv"); div.style.top = div.offsetTop + 1 + "px"; div.style.left = div.offsetLeft + 1 + "px"; }, 1000);
登錄后復(fù)制
示例
這是此示例的完整工作代碼 –
<!doctype html> <html> <head> <style> #movingDiv { position: relative; width: 200px; height: 200px; } </style> </head> <body> <div id="movingDiv"> This is my moving div! </div> <script> var interval = setInterval(function() { var div = document.getElementById("movingDiv"); div.style.top = div.offsetTop + 1 + "px"; div.style.left = div.offsetLeft + 1 + "px"; }, 1000); </script> </body> </html>
登錄后復(fù)制
上述代碼的逐行解釋 –
第 1 行 – 我們首先創(chuàng)建一個(gè) HTML document.
Line 3 – 我們創(chuàng)建一個(gè) head 元素。
Line 4 – 我們創(chuàng)建一個(gè)樣式元素。在這個(gè)樣式元素中,我們將放置我們的CSS代碼。
第5行 – 我們?yōu)槲覀兊膁iv創(chuàng)建一個(gè)CSS規(guī)則,id為“移動(dòng)Div”。我們將位置設(shè)置為
“relative”. We also set div 的寬度和高度。
Line 12 ? We create a body element. Inside of this body element, we will put our HTML code.
Line 13 ? We create a div with an id of “movingDiv“. Inside of this div, we put some text.
Line 14 ? We create a script element. Inside this script element, we will put our JavaScript 代碼。
Line 15 ? We create a variable called “interval“. We set this variable to the setInterval function. This function will move our div every 1000 milliseconds (1 second).
Line 16 ? We create a variable called “div”. We set this variable to the HTML element with an id of “movingDiv“.
Line 17 ? We use the CSS “top” property to move our div down 1 pixel.
Line 18 ? We use the CSS “left” property to move our div to the right 1 pixel.
Line 22 ? We end our HTML document.
In this tutorial, we went over how to create a moving div using JavaScript. We started off
通過創(chuàng)建一些 HTML 代碼。然后我們創(chuàng)建了一些 CSS 代碼。最后,我們創(chuàng)建了一些
JavaScript 代碼。
以上就是如何使用 JavaScript 創(chuàng)建一個(gè)移動(dòng)的 div?的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!