今天做一个js坦克移动的demo
首先在image文件夹中放入以下五张图片素材
创建html文件
<!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><style>body{background-image: url(images/grassland.png);}#mytank{/* 相对于页面窗口 *//* position: relative; *//* 父容器 */position: absolute;left: 10px;top: 200px;}</style>
</head>
<body><img src="images/right.png" id="mytank">
</body><script>// 获取属性var Omg = document.querySelector('img')// 获取图片var style = getComputedStyle(Omg)// 初始化图片位置var L = parseInt(style.left)var T = parseInt(style.top)//禁用右键 window.document.oncontextmenu = function(){return false}// 控制方向键window.onkeydown = function(e){switch(e.key){case "w":case 'ArrowUp':Omg.src="images/up.png"T=T-10Omg.style.top = T + 'px'break;case "s":case 'ArrowDown':Omg.src="images/down.png"T=T+10Omg.style.top = T + 'px'break;case "a":case 'ArrowLeft':Omg.src="images/left.png"L=L-10Omg.style.left = L + 'px'break;case "d":case 'ArrowRight':Omg.src="images/right.png"L=L+10Omg.style.left = L + 'px'break;}}
</script>
</html>
效果图(可移动)