先来看一个简单实例:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>动态添加样式title>
<style>
.first {
background-color: blueviolet;
}
.second {
display: block;
width: 240px;
height: 240px;
background-color: rgb(208, 226, 43);
}
.third {
display: block;
width: 640px;
height: 240px;
background-color: rgb(43, 116, 226);
}
style>
head>
<body>
<script src="../third_party_pack/vue/vue.js">script>
<div id="sagasw">
<div class="first" @click="real=!real" :class="{second:real,third:!real}">123div>
div>
<script>
new Vue({
el: '#sagasw',
data: {
real: false,
}
})
script>
body>
html>
点击效果 :
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>动态添加样式title>
<style>
.first {
background-color: blueviolet;
}
.second {
display: block;
width: 240px;
height: 240px;
background-color: rgb(208, 226, 43);
}
style>
head>
<body>
<script src="../third_party_pack/vue/vue.js">script>
<div id="sagasw">
<div class="first" @click="real=!real" :class="choose" >123div>
<input type="text" v-model="choose">
div>
<script>
new Vue({
el: '#sagasw',
data: {
choose:'',
real: false,
}
})
script>
body>
<body>
<script src="../third_party_pack/vue/vue.js">script>
<div id="sagasw">
<div class="first" :style="{backgroundColor:choose}">123div>
<input type="text" v-model="choose">
div>
<script>
new Vue({
el: '#sagasw',
data: {
choose: '',
}
})
script>
body>
<body>
<script src="../third_party_pack/vue/vue.js">script>
<div id="sagasw">
<div class="first" :style="{backgroundColor:color,width:width+'px'}" style="height: 50px;">div>
//也可以写background-color
<input type="text" v-model="color">
<input type="text" v-model="width">
div>
<script>
new Vue({
el: '#sagasw',
data: {
color: '',
width:'',
}
})
script>
body>
<body>
<script src="../third_party_pack/vue/vue.js">script>
<div id="sagasw">
<div class="first" :style="divStyle" style="height: 50px;">div>
<input type="text" v-model="color">
<input type="text" v-model="width">
div>
<script>
new Vue({
el: '#sagasw',
data: {
color: '',
width: '',
},
computed:{
divStyle:function(){
return{
backgroundColor:this.color,
width:this.width+"px",b
}
}
}
})
script>
body>
<body>
<script src="../third_party_pack/vue/vue.js">script>
<div id="sagasw">
<div class="first" :style="[divStyle,height+'px']" style="height: 50px;">div>
<input type="text" v-model="color">
<input type="text" v-model="width">
<input type="text" v-model="height">
div>
<script>
new Vue({
el: '#sagasw',
data: {
color: '',
width: '',
height:'',
},
computed:{
divStyle:function(){
return{
backgroundColor:this.color,
width:this.width+"px",
height:this.height+"px",
}
}
}
})
script>
body>