我正在学习javascript。我尝试使用setTimeout学习一些动画技术。
<script type="text/javascript">
var animate;
var moveImg=null;
function init(){
moveImg=document.getElementById("ashu");
moveImg.style.position="relative";
moveImg.style.left="1px";
return moveImg;
}
function start(){
while(moveImg.style.left!=null){
moveImg.style.left=parseInt(moveImg.style.left)+10+'px'
if(moveImg.style.left<"100px"){
animate=setTimeout(start,200);
}else{
clearTimeout(animate);
moveImg.style.left="0px";
}
}
function stop(){
clearTimeout(animate);
moveImg.style.left="0px";
}
window.onload=init;
</script>
html文件:
<body>
<img src="ashu.jpg" id="ashu" width="500px" height="250">
<br/>
<input type="button" onclick="start()" value="Start">
<br/>
<input type="button" onclick="stop()" value="Stop">
</body>
当我点击开始按钮时。没有任何事情发生。
答案 0 :(得分:0)
删除while
循环并使用与100
而非100px
的正确比较:
var animate;
var moveImg = null;
function init() {
moveImg = document.getElementById("ashu");
moveImg.style.position = "relative";
moveImg.style.left = "1px";
return moveImg;
}
function start() {
moveImg.style.left = parseInt(moveImg.style.left) + 10 + 'px'
if (parseInt(moveImg.style.left) < 100) {
animate = setTimeout(start, 200);
} else {
clearTimeout(animate);
moveImg.style.left = "0px";
}
}
function stop() {
clearTimeout(animate);
moveImg.style.left = "0px";
}
window.onload = init;
&#13;
<img src="http://lorempixel.com/100/100" id="ashu">
<br/>
<input type="button" onclick="start()" value="Start">
<br/>
&#13;
您可能还希望减少超时和左移以获得更流畅的动画:
moveImg.style.left = parseInt(moveImg.style.left) + 5 + 'px'
if (parseInt(moveImg.style.left) < 100) {
animate = setTimeout(start, 30);
}
或更好地使用requestAnimationFrame功能:
function start() {
moveImg.style.left = parseInt(moveImg.style.left) + 2 + 'px'
if (parseInt(moveImg.style.left) < 100) {
window.requestAnimationFrame(start);
} else {
moveImg.style.left = "0px";
}
}
答案 1 :(得分:0)
moveImg.style.left=(parseInt(moveImg.style.left)+10)+'px'
if((parseInt(moveImg.style.left)+10) < 100){
animate=setTimeout(start,200);
}else{
clearTimeout(animate);
moveImg.style.left="0px";
}