效果图
1 <style type="text/css"> 2 .content { 3 height: 800px; 4 width: 800px; 5 margin: 0 auto; 6 background-image: url(img/xz.png); 7 border: 1px solid black; 8 } 9 10 .xz { 11 height: 100px; 12 width: 100px; 13 background-image: url(img/bg.png); 14 position: relative; 15 } 16 17 .d1 { 18 height: 100px; 19 width: 100px; 20 margin-left: 100px; 21 background-color: grey; 22 } 23 </style>
CSS样式
<div id="app"> <div class="content"> <div class="xz" v-bind:style="{top:topValue+'px',left:leftValue+'px'}"> </div> <div class="d1"> </div> </div> </div>
app选择器div容器为最外面大盒子
content选择器div容器为小容器
xz选择器div容器为一个箱子
d1为障碍物
var vm = new Vue({
el: '#app',
data: {
topValue: 0,
leftValue: 0
},
创建Vue实例绑定app容器使用
data创建动态数据供html的箱子动态使用移动
topValue为控制上下移动
leftValue为控制左右移动
methods: { move(event) { console.log(event.keyCode); switch (event.keyCode) { case 37: if (this.leftValue <= 0 || this.leftValue == 200 && this.topValue == 100) { break; } this.leftValue -= 100; break; case 38: if (this.topValue <= 0 || this.leftValue == 100 && this.topValue == 200) { break; } this.topValue -= 100; break; case 39: if (this.leftValue >= 700 || this.leftValue == 0 && this.topValue == 100) { break; } this.leftValue += 100; break; case 40: if (this.topValue >= 700 || this.leftValue == 100 && this.topValue == 0) { break; } this.topValue += 100; break; default: break; } } },
在methods里自定义函数方法
定义move函数获取键盘触发事件控制移动方向
使用switch多分枝结构条件选择通过判断键盘的keyCode值来控制箱子的上下左右移动和障碍物的判断
mounted: function() {
document.addEventListener("keydown", this.move);
}
设置全局键盘触发函数,并调用methods函数方法移动箱子
相关知识:
- vue实例和容器是一一对应的
- 真实开发中只有一个vue实例,而且会配合着组件一起使用
- :style=" {fontSize: xxx}" 其中xxx是动态值。
;style="[a,b]"其中a、b是样式对象。