通过键盘监听实现盒子的移动
HTML部分
<p>
提示: 红色方块为键盘操作区域,您可以进行如下操作:
上:↑ 下:↓ 左:← 右:→ Ctrl + 1 : 背景变为绿色 Ctrl + 2 :
背景变为黄色 Ctrl + 3
: 背景变为蓝色 Ctrl + ↑ : 放大 Ctrl + ↓ : 缩小
</p>
<div class="box"></div>
<div class="b1"></div
Css部分
<style>
p {
white-space: pre;
line-height: 1.5;
color: gray;
}
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 100px;
left: 400px;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
.blue {
background-color: blue;
}
.bigger {
transform: scale(1.5);
}
.smaller {
transform: scale(0.7);
}
</style>
JavaScript部分
<script>
let box = document.querySelector('.box')
let _left = parseFloat(getComputedStyle(box).left)
let _top = parseFloat(getComputedStyle(box).top)
let rawBoxClass = box.className
// window.onkeydown = function (e) {
// console.log(e)
// if(e.keyCode == 38){
// console.log('keyup')
// box.style.top = `${--y}px`
// }
// if(e.keyCode == 49 && e.ctrlKey){
// box.classList.add('green')
// }
// }
//移动速度
let speed = 10
window.onkeydown = function(e) {
console.log(e)
if (e.keyCode == 38) {
_top -= speed
box.style.top = _top + "px"
}
if (e.keyCode == 40) {
_top += speed
box.style.top = _top + "px"
}
if (e.keyCode == 37) {
_left -= speed
box.style.left = _left + "px"
}
if (e.keyCode == 39) {
_left += speed
box.style.left = _left + "px"
}
if (e.keyCode == 49 && e.ctrlKey) {
box.className = rawBoxClass + " " + "green"
}
if (e.keyCode == 50 && e.ctrlKey) {
box.className = rawBoxClass + " " + "yellow"
}
if (e.keyCode == 38 && e.ctrlKey) {
box.classList.remove('smaller')
box.classList.add('bigger')
}
if (e.keyCode == 40 && e.ctrlKey) {
box.classList.remove('bigger')
box.classList.add('smaller')
}
}
</script>