如何用计时器移动 div?
How to move a div with a timer?
我用 console.log{"test")
进行了测试,它写入了多次,所以我知道计时有效,但 div 不会移动!
var myVar = setInterval(myTimer, 100);
function myTimer() {
var carre = document.getElementById("carre");
carre.style.marginLeft = carre.style.marginLeft + "10px";
}
<div id="carre" style="width:100px;height:100px;background-color:red;position:absolute;"></div>
你犯了两个错误。
- 您需要
parseInt
将 marginLeft
转换为数字,因为它 returns 带有 px
的数字。
- 其次,您应该只添加
10
,不添加 ""
,并在末尾添加 "px"
。
var myVar = setInterval(myTimer, 100);
function myTimer() {
var carre = document.getElementById("carre");
console.log()
carre.style.marginLeft = (parseInt(carre.style.marginLeft)||0) + 10 + 'px';
}
<div id="carre" style="width:100px;height:100px;background-color:red;position:absolute;"></div>
问题是您不能将字符串 ("10px") 添加到另一个字符串的末尾并期望它将其视为数学运算。两个值都不是数字。
这会起作用:
var myVar = setInterval(myTimer, 100);
function myTimer() {
var carre = document.getElementById("carre");
if (carre.style.marginLeft == "") {
carre.style.marginLeft = "10px";
} else {
carre.style.marginLeft = (parseInt(carre.style.marginLeft) + 10) + "px";
}
}
<div id="carre" style="width:100px;height:100px;background-color:red;position:absolute;"></div>
我用 console.log{"test")
进行了测试,它写入了多次,所以我知道计时有效,但 div 不会移动!
var myVar = setInterval(myTimer, 100);
function myTimer() {
var carre = document.getElementById("carre");
carre.style.marginLeft = carre.style.marginLeft + "10px";
}
<div id="carre" style="width:100px;height:100px;background-color:red;position:absolute;"></div>
你犯了两个错误。
- 您需要
parseInt
将marginLeft
转换为数字,因为它 returns 带有px
的数字。 - 其次,您应该只添加
10
,不添加""
,并在末尾添加"px"
。
var myVar = setInterval(myTimer, 100);
function myTimer() {
var carre = document.getElementById("carre");
console.log()
carre.style.marginLeft = (parseInt(carre.style.marginLeft)||0) + 10 + 'px';
}
<div id="carre" style="width:100px;height:100px;background-color:red;position:absolute;"></div>
问题是您不能将字符串 ("10px") 添加到另一个字符串的末尾并期望它将其视为数学运算。两个值都不是数字。
这会起作用:
var myVar = setInterval(myTimer, 100);
function myTimer() {
var carre = document.getElementById("carre");
if (carre.style.marginLeft == "") {
carre.style.marginLeft = "10px";
} else {
carre.style.marginLeft = (parseInt(carre.style.marginLeft) + 10) + "px";
}
}
<div id="carre" style="width:100px;height:100px;background-color:red;position:absolute;"></div>