innerHTML打破setInterval

时间:2015-09-01 09:56:16

标签: javascript setinterval innerhtml

有谁知道为什么会这样?放置图像,然后设置setInterval函数为其设置动画。然后将HTML添加到父div中会破坏动画。

document.getElementById('whiteboard').innerHTML = '<img id="mule" src="http://childscript.com/art/mule.png" />';  //image with id mule

csE = document.getElementById('mule');
setInterval(function(){ csE.style.transform = 'rotate(' + Math.floor(Math.random() * 90 -45) + 'deg)'; }, 100);

// following line breaks the code???
document.getElementById('whiteboard').innerHTML += 'hey';

JSfiddle:http://jsfiddle.net/gt6w3dhb/

1 个答案:

答案 0 :(得分:0)

因为在替换innerHTML时,它正在替换现有的dom元素。

在您的情况下,csE变量引用替换innerHTML

后dom中不存在的dom元素

所以解决方案是将新元素附加到dom,而不是使用innerHTML的字符串连接

document.getElementById('whiteboard').innerHTML = '<img id="mule" src="http://childscript.com/art/mule.png" />';

csE = document.getElementById('mule');
setInterval(function() {
  csE.style.transform = 'rotate(' + Math.floor(Math.random() * 90 - 45) + 'deg)';
}, 100);

var txt = document.createTextNod('hey');
document.getElementById('whiteboard').appendChild(txt)
<div id="whiteboard"></div>

相关问题