[英]Continuously Move div position using javascript
我想從左到右,然后從上到下連續移動我的div位置。
首先移動我的代碼停止。
請檢查https://jsfiddle.net/LLqmL33p/
function placeDiv(x_pos) {
var d = document.getElementById('boxed');
d.style.position = "absolute";
d.style.left = x_pos+'px';
setTimeout(function(){ placeDiv2(10); }, 1000);
}
function placeDiv2(y_pos) {
var d = document.getElementById('boxed');
d.style.position = "absolute";
d.style.top = y_pos+'px';
setTimeout(function(){ placeDiv(15); }, 1000);
}
placeDiv(10);
我不明白我現在能做什么?
該函數持續運行,但因為x_pos = 10和y_pos = 15始終具有相同的值,所以div不會移動,請嘗試:
function placeDiv(x_pos) {
var d = document.getElementById('boxed');
d.style.position = "absolute";
if(d.style.left=="")
{
var cur_left=0;
}
else
{
var cur_left=parseFloat(d.style.left);
}
d.style.left = (cur_left+x_pos)+'px';
setTimeout(function(){ placeDiv2(10); }, 1000);
}
function placeDiv2(y_pos) {
var d = document.getElementById('boxed');
//d.style.position = "absolute";
if(d.style.top=="")
{
var cur_top=0;
}
else
{
var cur_top=parseFloat(d.style.top);
}
d.style.top = (cur_top+y_pos)+'px';
setTimeout(function(){ placeDiv(15); }, 1000);
}
placeDiv(10);
我所做的是將x_pos和y_pos值添加到div的當前左側和頂部值。
這里是更新的小提琴: https : //jsfiddle.net/LLqmL33p/2/抱歉我的英語不好。
@keyframes move { 0%{ left: 0px; top: 0px; } 100%{ left: 100%; top: 100%; }} div { width: 100px; height: 100px; background: red; position: absolute; animation: move 10s linear infinite; }
<div></div>
setTimeOut意味着在指定的延遲之后執行一次 。
你似乎想要使用setInterval
https://jsfiddle.net/LLqmL33p/1/
////css
@keyframes move { 0%{ left: 0px; top: 0px; } 50%{ left: 80%; top: 80%; } 80%{left: 90%; top: 10%;} 100%{left: 0%; top: 0%;}}
div {
width: 100px;
height: 100px;
background: red;
position: absolute;
animation: move 10s linear infinite;
}
/////html
<div></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.