為什么timer不能再onload事件里聲明呢
<div id="item" class="main"><span id = "spare" class = "sp">分享</span></div>
<script type="text/javascript">
window.onload = function (){
var item=document.getElementById("item");
item.onmouseover = function(){
startMove(0);
}
item.onmouseout = function(){
startMove(-400);
}
}
var timer = null;
function startMove(target){
var item=document.getElementById("item");
clearInterval(timer);
timer? = setInterval (function(){
speed = (item.offsetLeft > target)?-10 : 10;
if (item.offsetLeft == target){
clearInterval(timer);
}
else{
item.style.left = item.offsetLeft + speed + "px";
}
},30)
}
</script>
2020-01-08
onload事件是頁面加載就執(zhí)行. 如果你在onload里面聲明 啟動(dòng)就會(huì)執(zhí)行一次,而不是鼠標(biāo)進(jìn)入執(zhí)行。