JS implementation of the static element automatically moving example
- 2020-03-30 02:38:40
- OfStack
An element is static, allowing it to move automatically on the screen.
This is a relatively simple problem, encountered in the learning, write it down.
This is a relatively simple problem, encountered in the learning, write it down.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
#sp1{
border: red solid ;
display: inline-block;
width: 30px;
height: 20px;
font-size: 20px;
text-align: center;
}
</style>
<script>
var timenum;
var mar=0;//A variable that controls the amount of movement
var flag = 0;//Implement a variable that controls left and right movement
//Implement a function that moves to the right
function moveright(){
sp1.style.marginLeft=mar+"px";
mar=mar+5;
}
//Implement a function that moves to the right
function moveleft(){
sp1.style.marginLeft=mar+"px";
mar=mar-5;
}
function go() {
var sp1 =document.getElementById("sp1");
var btn1 = document.getElementById("start");
if(!btn1.disabled){
btn1.disabled = true;
document.getElementById("pause").disabled=false;
}
sp1.innerHTML=parseInt(sp1.innerHTML)+1;
timenum = window.setTimeout(go,10);
if(flag==1){
window.setTimeout(moveleft,10);
}
if(flag==0){
window.setTimeout(moveright,10);
}
if(mar>(window.outerWidth)){
flag=1;
}
if(mar<0){
flag=0;
}
}
function stop(){
document.getElementById("start").disabled = false;
document.getElementById("pause").disabled=true;
window.clearTimeout(timenum);
}
</script>
</head>
<body>
<button id="start" <button id="pause" disabled> suspended </button>
<br/>
<span id="sp1">0</span>
</body>
</html>