黑馬vue---17、vue中通過屬性綁定綁定style行內樣式


黑馬vue---17、vue中通過屬性綁定綁定style行內樣式

一、總結

一句話總結:

如果屬性名中帶有短線必須加引號,比如: h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' }

h1 :style="styleObj1"

 

 

二、內容在總結中

1、使用內聯樣式

### 使用內聯樣式

1. 直接在元素上通過 `:style` 的形式,書寫樣式對象
```
<h1 :style="{color: 'red', 'font-size': '40px'}">這是一個善良的H1</h1>
```

2. 將樣式對象,定義到 `data` 中,並直接引用到 `:style`
+ 在data上定義樣式:
```
data: {
h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' }
}
```
+ 在元素中,通過屬性綁定的形式,將樣式對象應用到元素中:
```
<h1 :style="h1StyleObj">這是一個善良的H1</h1>
```

3. `:style` 中通過數組,引用多個 `data` 上的樣式對象
+ 在data上定義樣式:
```
data: {
h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' },
h1StyleObj2: { fontStyle: 'italic' }
}
```
+ 在元素中,通過屬性綁定的形式,將樣式對象應用到元素中:
```
<h1 :style="[h1StyleObj, h1StyleObj2]">這是一個善良的H1</h1>
```

 

 

2、代碼

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5   <meta charset="UTF-8">
 6   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7   <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8   <title>Document</title>
 9   <script src="./lib/vue-2.4.0.js"></script>
10 </head>
11 
12 <body>
13   <div id="app">
14     <!-- 對象就是無序鍵值對的集合 -->
15     <!-- <h1 :style="styleObj1">這是一個h1</h1> -->
16 
17     <h1 :style="[ styleObj1, styleObj2 ]">這是一個h1</h1>
18   </div>
19 
20   <script>
21     // 創建 Vue 實例,得到 ViewModel
22     var vm = new Vue({
23       el: '#app',
24       data: {
25         styleObj1: { color: 'red', 'font-weight': 200 },
26         styleObj2: { 'font-style': 'italic' }
27       },
28       methods: {}
29     });
30   </script>
31 </body>
32 
33 </html>

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM