示例一 使用键盘控制小球:
效果图展示:
代码展示:
<!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>
.f {
width: 1200px;
height: 800px;
border: 1px dashed red;
position: relative;
}
.z {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: aqua;
position: absolute;
left: 550px;
top: 350px;
}
</style>
</head>
<body>
<div class="f">
<div id="ball" class="z"></div>
</div>
</body>
<script>
let ball = document.getElementById('ball')
let x = 50, y = 50
let dy = 10
let dx = 10;
document.onkeydown = function (e) {
console.log(e.keyCode)
switch (e.keyCode) {
case 38:
console.log('上')
y -= dy
ball.style.top = y - 50 + 'px'
break;
case 40:
console.log('下')
y += dy
ball.style.top = y - 50 + 'px'
break;
case 37:
x -= dx
console.log('左')
ball.style.left = x - 50 + 'px'
break;
case 39:
console.log('右')
x += dx
ball.style.left = x - 50 + 'px'
break;
}
}
</script>
</html>
1. 键盘事件:在JavaScript中,可以通过keydown、keyup和keypress事件来捕捉键盘按键操作。
2. event对象:当键盘事件被触发时,JavaScript会传递一个event对象作为参数给事件处理函数。
3. keyCode属性:event对象具有一个keyCode属性,它存储了按下按键的字符的数字码。
总而言之,JavaScript的keyCode属性可以用来获取按下按键的数字码,但由于它被认为是不可靠和过时的,更好的替代方案是使用event.key属性来获取按键的字符串值。
示例二:三国英雄归为
效果图展示:
代码展示:
<style>
/*
操控单个元素,布局方式:子元素绝对定位,父元素相对定位
所有子元素,left和top都是相对父元素的左上顶点
因此每个子元素的left和top出生在不一样
父元素流式布局:
操控批量的元素:flex,子元素相对定位
每个子元素都是相对自身的初始值位置
*/
.f1,
.f2 {
/*流式布局*/
display: flex;
/*每个子元素均匀分布*/
justify-content: space-around;
}
.f1>img {
width: 200px;
height: 300px;
position: relative;
top: 0;
left: 0;
}
.f2 {
margin-top: 150px;
}
.f2>div {
width: 200px;
height: 300px;
border: 1px solid rebeccapurple;
text-align: center;
line-height: 300px;
}
</style>
//HTML区块
<div class="f1">
<img class="tu1" src="../imgs/曹操.jpg" onclick="move1(this,0)" />
<img class="tu2" src="../imgs/貂蝉.webp" onclick="move1(this,1)" />
<img class="tu3" src="../imgs/关羽.webp" onclick="move1(this,2)" />
<img class="tu4" src="../imgs/刘备.jpg" onclick="move1(this,3)" />
<img class="tu5" src="../imgs/刘协.webp" onclick="move1(this,4)" />
<img class="tu6" src="../imgs/孙权.webp" onclick="move1(this,5)" />
</div>
<div class="f2">
<div>刘协</div>
<div>曹操</div>
<div>貂蝉</div>
<div>关羽</div>
<div>刘备</div>
<div>孙权</div>
</div>
JavaScript区块:
<script>
//定义一个坐标对象,记录当前操作的元素的位置
let pos = { x: 0, y: 0 }
//定义一个数组,存放6哥对象,独立的记录每个对象的运动坐标
let arr = [{ x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 },{ x: 0, y: 0 }]
function move1(img, i) {
//pos表示当前正在操作的对象
pos = arr[i]
console.log(img)
document.onkeydown = function (e) {
switch (e.keyCode) {
// 上
case 37:
pos.x -= 5
img.style.left = pos.x + 'px'
break;
// 下
case 39:
pos.x += 5
img.style.left = pos.x + 'px'
break;
// 左
case 38:
pos.y -= 5
img.style.top = pos.y + 'px'
break;
// 右
case 40:
pos.y += 5
img.style.top = pos.y + 'px'
break;
}
}
}
</script>