vue实现div 点击变色
实现点击变色效果
在Vue中实现div点击变色可以通过绑定点击事件和动态样式来实现。以下是几种常见方法:
方法一:使用v-bind:class
通过切换CSS类名实现颜色变化:
<template>
<div
:class="{ 'active': isActive }"
@click="isActive = !isActive"
>
点击我变色
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
}
}
}
</script>
<style>
div {
width: 200px;
height: 100px;
background-color: #ccc;
cursor: pointer;
}
.active {
background-color: #42b983;
}
</style>
方法二:使用内联样式
直接通过v-bind:style动态修改样式:
<template>
<div
:style="{ backgroundColor: currentColor }"
@click="toggleColor"
>
点击我变色
</div>
</template>
<script>
export default {
data() {
return {
currentColor: '#ccc',
colors: ['#ccc', '#42b983', '#ff0000'],
currentIndex: 0
}
},
methods: {
toggleColor() {
this.currentIndex = (this.currentIndex + 1) % this.colors.length
this.currentColor = this.colors[this.currentIndex]
}
}
}
</script>
<style>
div {
width: 200px;
height: 100px;
cursor: pointer;
}
</style>
方法三:使用计算属性
当颜色逻辑较复杂时,可使用计算属性:
<template>
<div
:style="divStyle"
@click="toggleActive"
>
点击我变色
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
}
},
computed: {
divStyle() {
return {
width: '200px',
height: '100px',
cursor: 'pointer',
backgroundColor: this.isActive ? '#42b983' : '#ccc'
}
}
},
methods: {
toggleActive() {
this.isActive = !this.isActive
}
}
}
</script>
方法四:使用多个div切换
如果需要多个div之间互斥变色:
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
:class="{ 'active': activeIndex === index }"
@click="activeIndex = index"
>
Div {{ index + 1 }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [1, 2, 3, 4],
activeIndex: null
}
}
}
</script>
<style>
div div {
width: 200px;
height: 50px;
margin: 5px;
background-color: #eee;
cursor: pointer;
}
.active {
background-color: #42b983;
}
</style>
这些方法可根据实际需求选择使用,v-bind:class适合简单的类名切换,v-bind:style适合更灵活的样式控制,计算属性适合复杂逻辑,多个div切换则适合互斥选择场景。







