<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 300px;
height: 300px;
border-radius: 50%;
background-color: aliceblue;
position: absolute;
line-height: 300px;
text-align: center;
}
</style>
</head>
<body>
<div id="q">单击移动</div>
</body>
<script>
//定时器
var timer;
//控制小球来回移动
var pd = true;
var a = document.getElementById("q");
//移动的像素
var aaa = 1;
//控制小球是否移动
var chishu = 0;
function yidon() {
if (chishu % 2 == 1) {
a.innerHTML="小球停止";
if (aaa <= 100 && pd) {
//向右移动
aaa++;
a.style.left = aaa + 'px';
} else {
//向左移动并通过pd控制
pd = false;
aaa--;
a.style.left = aaa + 'px';
}
if (aaa == 0) {
//可以让它向右了
pd = true;
}
} else if (chishu % 2 == 0) {
//让他停止
a.style.left = aaa + 'px';
a.innerHTML="小球移动";
}
}
document.getElementById("q").onclick = function () {
chishu++;
clearInterval(timer); // 清除之前的定时器 要不然速度会变快
timer = setInterval(yidon, 100);
}
</script>
</html>
分享案例 私信交流 做一个有爱的码农!!!