CSS 樣式和類
基礎語法
CSS 樣式可以理解爲一系列的鍵值對,其中的每一對描述了一個特定的樣式,例如組件的寬或者高。
width: 400; height: 50; ...
鍵值對的形式是 prop-name: prop-value;
。鍵名是 prop-name
,鍵值是 prop-value
。 一般情況下,鍵名按照連接符的方式進行命名,鍵和值之間由冒號 :
進行分隔,每對鍵值之間由分號 ;
進行分隔。
在 Weex 頁面上樣式有兩種形式:
<template>
中的style
特性<style>
樣式表
<template>
中的 style
特性
在 style
特性中編寫樣式,例如:
<template>
<div style="width: 400; height: 50;">
...
</div>
</template>
這段代碼的意思是 <div>
組件的寬和高分別爲 400 像素和 50 像素。
<style>
樣式表
例如:
<style>
.wrapper { width: 600; }
.title { width: 400; height: 50; }
.highlight { color: #ff0000; }
</style>
樣式表包含了多個樣式規則,每條規則有一個對應的類,以及由 {...}
包括的若干條樣式。例如:
.title { width: 400; height: 50; }
class
特性
<template>
標籤中的 class
特性值用來匹配 <style>
樣式表中的一個或多個 class 名,多個 class name 之間由空格分隔。例如:
<template>
<div class="wrapper">
<text class="title">...</text>
<text class="title highlight">...</text>
</div>
</template>
<style>
.wrapper { width: 600; }
.title { width: 400; height: 50; }
.highlight { color: #ff0000; }
</style>
這段代碼的含義是 <div>
組件的寬度是 600 像素,兩個 <text>
組件的尺寸爲 400x50,其中第二個文本組件是紅色字。
注意事項
- 爲了簡化頁面設計和實現,屏幕的寬度統一爲 750 像素,不同設備屏幕都會按照比例轉化爲這一尺寸進行長度計算。
- 標準 CSS 支持很多樣式選擇器,但 Weex 目前只支持單個 class name 的選擇器。
- 標準 CSS 支持很多的長度單位,但 Weex 目前只支持像素,並且
px
單位可以忽略不寫,直接使用對應的數值。更多詳情請查看通用樣式。 - 子元素的樣式不會繼承自父元素,這一點與標準 CSS 不同,比如
color
和font-size
等樣式作用在<text>
上層的<div>
上是無效的。 - 標準 CSS 包含了非常多的樣式屬性,但 Weex 只支持了其中的一部分,比如盒模型、flexbox、position 等佈局屬性,以及
font-size
、color
等其它樣式。
與數據綁定結合
請查閱數據綁定中有關 style
和 class
特性的相關部分。這裏簡單舉個例子:
<template>
<div>
<text style="font-size: {{fontSize}};">Alibaba</text>
<text class="large {{textClass}}">Weex Team</text>
</div>
</template>
<style>
.large {font-size: 32;}
.highlight {color: #ff0000;}
</style>
<script>
module.exports = {
data: {
fontSize: 32,
textClass: 'highlight'
}
}
</script>
事件處理
Weex 允許對 <template>
中的元素綁定事件處理函數。
基本語法
以 on...
開頭的就是用於綁定事件的特性,特性名中 on
之後的部分就是事件的類型,特性的值就是處理該事件的函數名。函數名外不需要添加 mustache 語法中的大括號。例如:
<template>
<div>
<text onclick="toggle">Toggle: {{result}}</text>
</div>
</template>
<script>
module.exports = {
data: {
result: true
},
methods: {
toggle: function () {
this.result = !this.result
}
}
}
</script>
內聯事件處理參數
同時我們也支持在事件綁定的特性值中內聯寫明被傳入的參數。例如:
<template>
<div>
<text onclick="update(1, 2)">Result: {{result}}</text>
</div>
</template>
<script>
module.exports = {
data: {
result: '<empty>'
},
methods: {
update: function (x, y) {
this.result = x + y
}
}
}
</script>
特殊的內聯事件處理參數
額外的,在這種內聯的事件綁定寫法中,你可以使用一個特殊的參數 $event
,代表事件描述對象,即默認事件處理函數的第一個參數。所以 <template>
中的 οnclick="foo"
和 οnclick="foo($event)"
是等價的,$event
的用法可以更多參考下面的例子
<template>
<div>
<text onclick="update($event, 1, 2)">Result: {{result}}</text>
</div>
</template>
<script>
module.exports = {
data: {
result: '<empty>'
},
methods: {
update: function (e, x, y) {
this.result = e.type + (x + y)
}
}
}
</script>
事件描述對象
每當一次事件被觸發的時候,都會產生一個事件描述對象,該對象會默認作爲第一個參數傳遞給事件處理函數,或以 $event
形參的方式出現在內聯事件處理函數中。
每個事件描述對象至少包含以下幾個特性:
type
(string
): 事件名稱, 如:click
target
(Element
): 目標元素timestamp
(number
): 事件觸發時的時間戳數字