[英]Continuously Move div position using javascript
I want to move my div position continuously left to right then top to bottom. 我想从左到右,然后从上到下连续移动我的div位置。
After first move my code stop. 首先移动我的代码停止。
please check https://jsfiddle.net/LLqmL33p/ 请检查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);
I cant understand what can I do now? 我不明白我现在能做什么?
The function keeps running continuously, but because the x_pos=10 and y_pos=15 have same value always, the div will not move, try this: 该函数持续运行,但因为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);
What I do is I add the x_pos and y_pos value to current left and top value of the div. 我所做的是将x_pos和y_pos值添加到div的当前左侧和顶部值。
here is the updated fiddle: https://jsfiddle.net/LLqmL33p/2/ and sorry for my bad English. 这里是更新的小提琴: 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 is meant to execute once , after the specified delay. setTimeOut意味着在指定的延迟之后执行一次 。
It would appears you'd like to use setInterval 你似乎想要使用setInterval
https://jsfiddle.net/LLqmL33p/1/ 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.