Vue3 实现 DIV 上下左右移动 - 完整教程及示例代码
要实现 Vue3 中控制 div 上下左右移动的功能,可以按照以下步骤进行:
- 在 Vue 组件中,定义一个 data 属性来存储 div 的位置信息,如'top'、'left'。
- 在模板中,使用'v-bind' 指令将 div 的'top' 和'left' 属性绑定到 data 属性上。
- 使用'v-on' 指令监听键盘事件,当按下上下左右箭头键时,调用对应的方法进行位置的改变。
- 在方法中,根据按下的箭头键的不同,更新 data 属性中的位置信息。
- 在样式中,使用绝对定位和'top'、'left' 属性来控制 div 的位置。
下面是一个示例代码:
<template>
<div class="container">
<div class="box" :style="{ top: top + 'px', left: left + 'px' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
top: 0,
left: 0
};
},
methods: {
move(direction) {
switch (direction) {
case 'up':
this.top -= 10;
break;
case 'down':
this.top += 10;
break;
case 'left':
this.left -= 10;
break;
case 'right':
this.left += 10;
break;
}
}
},
mounted() {
window.addEventListener('keydown', (e) => {
switch (e.key) {
case 'ArrowUp':
this.move('up');
break;
case 'ArrowDown':
this.move('down');
break;
case 'ArrowLeft':
this.move('left');
break;
case 'ArrowRight':
this.move('right');
break;
}
});
}
};
</script>
<style>
.container {
position: relative;
width: 400px;
height: 400px;
border: 1px solid #ccc;
}
.box {
position: absolute;
top: 0;
left: 0;
width: 50px;
height: 50px;
background-color: red;
}
</style>
在以上示例代码中,'.container' 是一个容器,'.box' 表示要移动的 div。通过监听键盘事件,按下上下左右箭头键时,调用'move' 方法来改变 div 的位置。通过绑定'top' 和'left' 属性,实现 div 的位置控制。
原文地址: https://www.cveoy.top/t/topic/piXz 著作权归作者所有。请勿转载和采集!