html_and_vue/vue/10_绑定样式/绑定样式.html

94 lines
2.6 KiB
HTML
Raw Normal View History

2023-09-15 16:17:19 +00:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.basic {
width: 400px;
height: 100px;
border: 1px solid black;
}
.normal {
background-color: skyblue;
}
.happy {
background-color: red;
}
.sad {
background-color: green;
}
.zhangjun1 {
background-color: orange;
}
.zhangjun2 {
border-radius: 10px;
}
.zhangjun3 {
font-size: 40px;
}
</style>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<!-- 绑定class样式:字符串写法,适用于样式的类名不确定,需要动态指定 -->
<div class="basic" :class="mood" @click="changeMood">{{name}}</div><br><br>
<!-- 绑定class样式:数组写法,适用于要绑定的样式个数不确定、名字也不确定 -->
<div class="basic" :class="classArr">{{name}}</div><br><br>
<!-- 绑定class样式:对象写法,适用于要绑定的样式个数确定、名字确定, 但要动态决定用不用 -->
<div class="basic" :class="classObj">{{name}}</div><br><br>
<!-- 绑定style(内联)样式:对象写法 -->
<div class="basic" :style="styleObj">{{name}}</div><br><br>
<!-- 绑定style(内联)样式:对象写法 -->
<div class="basic" :style="styleArr">{{name}}</div>
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
new Vue({
el:'#root',
data:{
name:'请叫我张钧',
mood:'normal',
classArr:['zhangjun1','zhangjun2','zhangjun3'],
classObj:{
zhangjun1:false,
zhangjun2:true
},
styleObj:{
color:'red',
fontSize:'30px' // 在配置对象中,key:value的形式中,key中不能出现"-", 要将"-"后的单词首字母大写,写成大驼峰的形式
},
styleArr:[
{
color:'red',
fontSize:'30px'
},
{
backgroundColor:'red'
}
]
},
methods: {
changeMood(){
const arr = ['happy','sad','normal'] // 创建一个数据
const index = Math.floor(Math.random()*3)
this.mood = arr[index]
}
},
})
</script>
</html>