從 IE5 開始,瀏覽器支援在 CSS 中使用 expression,用來把 CSS 屬性與一段 JavaScript 表達式綁在一起。這裡的 CSS 屬性可以是元素固有的,也可以是你自訂的。也就是說,屬性值不再是一個固定字串,而是等於某段 JavaScript 運算的結果。在表達式裡,你可以直接引用元素自身的屬性與方法,也能使用其他瀏覽器物件,寫起來就像在該元素的一個成員函式裡操作一樣。
例如,你可以依瀏覽器視窗大小來擺放元素位置:
#myDiv {
position: absolute;
width: 100px;
height: 100px;
left: expression(document.body.offsetWidth - 110 + "px");
top: expression(document.body.offsetHeight - 110 + "px");
background: red;
}
例如,想消除頁面上所有連結被點擊後出現的虛線框,傳統做法是每個連結都寫:
<a href="link1.htm" onfocus="this.blur()">link1</a>
<a href="link2.htm" onfocus="this.blur()">link2</a>
<a href="link3.htm" onfocus="this.blur()">link3</a>
乍看之下用 expression 沒什麼優勢,但如果頁面上有幾十甚至上百個連結,你還會一個個機械式複製貼上嗎?兩相比較,哪種寫法產生的冗餘程式碼更多,一目了然。
改用 expression 的寫法如下:
<style type="text/css">
a { star : expression(onfocus=this.blur) }
</style>
<a href="link1.htm">link1</a>
<a href="link2.htm">link2</a>
<a href="link3.htm">link3</a>
說明:這裡的 star 是你自訂的屬性名稱,可任意命名;expression 括號裡放的是 JS 腳本。別忘了自訂屬性與 expression 之間要有冒號,而且因為本質仍是 CSS,所以要寫在 style 標籤內而非 script 裡。一句話就能解決整頁的虛線框問題。
不過先別高興太早。如果你想做的是「隨滑鼠移入移出改變文字框顏色」這類涉及 CSS 屬性變化的效果,直接寫:
input {star : expression(onmouseover=this.style.backgroundColor="#FF0000"; onmouseout=this.style.backgroundColor="#FFFFFF")}
結果會跳腳本錯誤。正確做法是把樣式定義包進函式裡:
<style type="text/css">
input {star : expression(onmouseover=function(){this.style.backgroundColor="#FF0000"}, onmouseout=function(){this.style.backgroundColor="#FFFFFF"}) }
</style>
除非真的必要,否則不建議使用 expression,因為它對瀏覽器資源的消耗相對較高。
用 CSS 樣式時我們都知道,可以定義一批物件的 class 來套用同一組樣式以統一介面。但如果想統一「事件」呢?例如頁面上有無數個 <img src="**.jpg">,要如何做到滑鼠移過時把 src 換成 **_over.jpg?答案就是 expression。CSS 寫法如下:
/* 替換圖片 CSS */
#imgScript {
star:expression(
onmouseover = function() {
if(this.hover != null){
this.name = this.src;
this.src = this.src.replace('.jpg', '_over.jpg');
this.HasChg = 1;
}
},
onmouseout = function() {
if(this.HasChg != null){
this.src = this.name;
this.HasChg = null;
}
}
)
} /* end imgScript */