IE5 之後支援在 CSS 中使用 expression(),把樣式屬性與一段 JavaScript 表達式綁在一起。屬性值不再是一個固定字串,而是表達式計算出來的結果。表達式裡可以直接引用元素自身的屬性與方法,也能存取其他瀏覽器物件,寫起來就像在該元素的成員函式中運作。
最經典的例子是讓元素永遠貼在視窗右下角:
#myDiv {
position: absolute;
width: 100px;
height: 100px;
left: expression(document.body.offsetWidth - 110 + "px");
top: expression(document.body.offsetHeight - 110 + "px");
background: red;
}
視窗一縮放,元素位置自動重算,完全不需要 resize 事件。
常見需求是消除點擊連結後出現的虛線框。傳統寫法得在每個標籤上動手:
<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>
三個還好,若頁面上有幾十上百個連結,這種 Ctrl+C / Ctrl+V 就顯得可笑了。改用 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 語句,而 custom 屬性與 expression 之間那個冒號不能省——畢竟本質上它還是 CSS,所以整段必須寫在 style 標籤內而非 script 裡。
如果你的目的是觸發「屬性變化」型的效果,直接寫會出錯。例如想讓輸入框在滑鼠移入時變色,直覺寫法如下:
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>
<input type="text">
<input type="text">
<input type="text">
expression 會被反覆求值——只要涉及到的屬性變動,瀏覽器就可能重算一次,對 CPU 的消耗遠高於一般樣式。在現代瀏覽器上它早已被移除,而它想解決的問題,現在有 CSS 變數、calc()、clamp() 與 requestAnimationFrame 等正規工具可用。認識它是為了讀懂舊程式碼,不是為了沿用。