Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
JS sports foundation
Framework of the campaign
At the beginning of the movement, has been shut down timer
And stopping the movement apart (if / else)
Here we use an example to explain:
Example: a circular movement are controlled by the left and right stop button (implemented in code)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
width: 150px;
height: 150px;
background: skyblue;
position: absolute;
left: 10px;
top: 50px;
border-radius: 50%;
}
</style>
</head>
<body>
<button class="btn-r">向右移动</button>
<button class="btn-l">向左移动</button>
<button class="btn-stop">停止</button>
<div class="box"></div>
<script>
var box = document.querySelector('.box');
var t;
//向右移动
document.querySelector('.btn-r').onclick = function () {
clearInterval(t);//停止正在起作用的定时器
t = setInterval(moveHor, 20, 10);//将参数放到事件参数之后
};
//停止
document.querySelector('.btn-stop').onclick = function () {
clearInterval(t);
};
//向左移动
document.querySelector('.btn-l').onclick = function () {
clearInterval(t);//停止正在起作用的定时器
t = setInterval(moveHor, 20, -10);
};
//水平移动
function moveHor(speed) {
var l = window.getComputedStyle(box, null).left;
l = parseFloat(l); //去掉单位
box.style.left = l + speed + "px";
}
</script>
</body>
</html>