vue实现盒子平移
Vue 实现盒子平移的方法
使用 CSS Transition 和 v-bind:style
通过 Vue 的 v-bind:style 动态绑定 CSS 样式,结合 transition 实现平滑的平移效果。
<template>
<div>
<button @click="moveBox">移动盒子</button>
<div
class="box"
:style="{ transform: `translateX(${offset}px)` }"
></div>
</div>
</template>
<script>
export default {
data() {
return {
offset: 0
}
},
methods: {
moveBox() {
this.offset += 50;
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
transition: transform 0.3s ease;
}
</style>
使用 CSS Animation 和动态类名
通过 Vue 的动态类名绑定触发 CSS 动画实现平移。
<template>
<div>
<button @click="toggleMove">移动盒子</button>
<div
class="box"
:class="{ 'move-right': isMoved }"
></div>
</div>
</template>
<script>
export default {
data() {
return {
isMoved: false
}
},
methods: {
toggleMove() {
this.isMoved = !this.isMoved;
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
transition: transform 0.3s ease;
}
.move-right {
transform: translateX(200px);
}
</style>
使用 Vue Transition 组件
Vue 的 <transition> 组件可以结合 CSS 实现更复杂的动画效果。
<template>
<div>
<button @click="show = !show">切换盒子</button>
<transition name="slide">
<div v-if="show" class="box"></div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
}
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s;
}
.slide-enter, .slide-leave-to {
transform: translateX(100px);
}
</style>
使用 GSAP 库实现高级动画
对于更复杂的动画需求,可以使用 GSAP 库实现平滑的平移效果。
<template>
<div>
<button @click="animateBox">动画移动</button>
<div ref="box" class="box"></div>
</div>
</template>
<script>
import { gsap } from 'gsap';
export default {
methods: {
animateBox() {
gsap.to(this.$refs.box, {
x: 200,
duration: 1,
ease: "power2.out"
});
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
}
</style>
响应式窗口大小变化的平移
结合 Vue 的 resize 事件监听实现响应式平移。
<template>
<div>
<div
class="box"
:style="{ transform: `translateX(${dynamicOffset}px)` }"
></div>
</div>
</template>
<script>
export default {
data() {
return {
dynamicOffset: 0
}
},
mounted() {
window.addEventListener('resize', this.handleResize);
this.handleResize();
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.dynamicOffset = window.innerWidth * 0.1;
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
transition: transform 0.3s ease;
}
</style>






