<style type="text/css"> div{ width: 100px; height: 100px; background-color: orange; position: absolute; } </style>
js代码:
<script type="text/javascript">
var div0 = document.getElementById("div0");
var left = 0;
var bool = true;
setInterval(animation,1000);
var time = 0;
div0.addEventListener("click",clickHandler);
function clickHandler(e) {
bool=!bool;
}
function animation(){
if(!bool) return;
console.log("已经过来"+time+"秒");
left+=20;
div0.style.left = left+"px";
}
</script>
总结:
如果需要让正方形定时移动,需要使用到setInterval,setInterval(函数名,定时时间)。然后获取正方形的id,并且给正方形添加一个点击事件,这个点击事件主要是来控制正方形的移动与暂停。
如果需要点击空白界面来控制正方形的移动与暂停,只需要将div0改为document即可
使用setInterval来控制正方形的移动的频率(每隔1秒),鼠标点击停止移动,当再次点击恢复移动
原文:https://www.cnblogs.com/MySweetheart/p/12287621.html