###代码实现
<!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>坦克</title>
</head>
<style>
div{
width: 500px;
margin: 50px auto;
}
div.content{
height: 300px;
border: 1px solid red;
position: relative;
}
img{
position: absolute;
}
img:last-child{
margin-top: 70px;
}
</style>
<script>
window.onload =function(){
var btns = document.getElementsByTagName('button')
var imgs = document.images
var sapn = document.getElementsByTagName('span')[0]
//手动移动
btns[0].onclick = function(){
if(imgs[0].offsetLeft>405){
imgs[0].style.left = 0+'px'
}
imgs[0].style.left = imgs[0].offsetLeft+10+'px'
}
//发射
btns[1].onclick = function(){
imgs[0].style.left = 0+'px'
imgs[1].style.left = 0+'px'
if(Number(sapn.innerHTML)==0){
sapn.innerHTML = 5;
}
var num = Number(sapn.innerHTML)
function handler(){
sapn.innerHTML = --num;
var id;
id = setTimeout(handler,1000)
if(num<=0){
clearTimeout(id)
imgs[0].style.left = imgs[0].offsetLeft+300+'px'
}
}
handler();
}
//赛跑
btns[2].onclick = function(){
imgs[0].style.left = 0+'px'
imgs[1].style.left = 0+'px'
var id = setInterval(function(){
var rand1 = parseInt(Math.random()*10+1)
var rand2 = parseInt(Math.random()*10+1)
imgs[0].style.left = imgs[0].offsetLeft +rand1 +'px'
imgs[1].style.left = imgs[1].offsetLeft +rand2 +'px'
if(imgs[0].offsetLeft>405 || imgs[1].offsetLeft>405){
clearInterval(id)
if(imgs[0].offsetLeft>405){
alert('tanke1胜')
}else{
alert('tanke2胜')
}
}
},100)
}
//自由移动
btns[3].onclick =function(){
var tanke1 = imgs[0]
function run(){
var id1 = setInterval(function(){
tanke1.style.left = tanke1.offsetLeft +10+'px'
if(tanke1.offsetLeft>405){
clearInterval(id1)
tanke1.src = './tanke_down.jpg'
var id2 = setInterval(function(){
tanke1.style.top = tanke1.offsetTop + 10 +'px'
if(tanke1.offsetTop>200){
clearInterval(id2)
tanke1.src = './tanke_left.jpg'
var id3 = setInterval(function(){
tanke1.style.left = tanke1.offsetLeft - 10 +'px'
if(tanke1.offsetLeft<10){
clearInterval(id3)
tanke1.src = './tanke_up.jpg'
var id4 = setInterval(function(){
tanke1.style.top = tanke1.offsetTop - 10 +'px'
if(tanke1.offsetTop<10){
clearInterval(id4)
tanke1.src = './tanke_right.jpg'
run();
}
},100)
}
},100)
}
},100)
}
},100)
}
run();
}
}
</script>
<body>
<div class="btns">
<button>手动移动</button>
<button>发射</button>
<button>赛跑</button>
<button>自由移动</button>
<span>5</span>
</div>
<div class="content">
<img src="./tanke_right.jpg" alt="">
<img src="./tanke_right.jpg" alt="">
</div>
</body>
</html>
想要图片可以访问该地址进行下载或者浏览该代码效果
链接: tanke.html.