当我单击div框时,我似乎无法触发代码,它只是一直运行onload。
<div id='tank' onclick="timer" style="position:relative; left:100px; top:240px;border- radius:360px;
background-color:green; height:100px; width:100px;"></div>
<script type="text/javascript">
(function () {
// don't leak variables into the global scope - think "variable = carbon dioxide"
var elem = document.getElementById('tank'), pos = 100,
timer = setInterval(function() {
pos++;
elem.style.left = pos+"px";
if( pos == 290) clearInterval(timer);
},12);
})();
答案 0 :(得分:2)
(function () {
//...
}());
立即运行函数内部的代码,因此难怪您的代码在页面加载时运行。
onclick="timer"
什么都不做。这与编写类似的内容相同:
var foo = 42;
foo; // <- this does not do anything
更糟糕的是,如果未定义timer
,则会引发错误(在您的示例中就是这种情况)。
您需要做的是将一个函数指定为元素的click事件处理程序。例如:
document.getElementById('tank').onclick = function() {
var elem = this,
pos = 100,
timer = setInterval(function() {
pos++;
elem.style.left = pos+"px";
if( pos == 290) clearInterval(timer);
},12);
};
(并从HTML中移除onclick="timer"
)
我建议您阅读the excellent articles at quirksmode.org以了解有关事件处理的更多信息。
答案 1 :(得分:0)
<div id='tank' onclick="timer()" style="position:relative; left:100px; top:240px;border-radius:360px; background-color:green; height:100px; width:100px;">
</div>
<script type="text/javascript">
function timer (){
alert("h");
var elem = document.getElementById('tank'), pos = 100,
timer = setInterval(function() {
pos++;
elem.style.left = pos+"px";
if( pos == 290) clearInterval(timer);
},12);
}
</script>
对您的代码进行轻微修改。