Jor*_*mon 0 javascript settimeout
我需要在for循环中获取此代码.所以我不必写4次,我只是无法使其工作.
setTimeout(
function(){
document.getElementById("square").style.left="0px";
},0);
setTimeout(
function(){
document.getElementById("square").style.left="100px";
},1000);
setTimeout(
function(){
document.getElementById("square").style.left="200px";
},2000);
setTimeout(
function(){
document.getElementById("square").style.left="300px";
},3000);
Run Code Online (Sandbox Code Playgroud)
我到目前为止的回答是这样的
for (i = 0; i <=300; i=i+100) {
j = i*10;
setTimeout(
function (){
document.getElementById("square").style.left=i+"px";
}, j);
};
Run Code Online (Sandbox Code Playgroud)
干得好:
var square = document.getElementById('square');
for (var i = 0; i <= 3; i++) {
setTimeout(function() {
square.style.left = i * 100 + 'px';
}, i * 1000);
}
Run Code Online (Sandbox Code Playgroud)
更新(现在使用闭包)
var square = document.getElementById('square');
for (var i = 0; i <= 3; i++) {
setTimeout(setLeft(square, i * 100), i * 1000);
}
function setLeft(element, offset) {
return function() {
element.style.left = offset + 'px';
};
}
Run Code Online (Sandbox Code Playgroud)