DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
expression:把 JavaScript 寫進 CSS 的舊世代特效手法
編輯:CSS進階教程     

IE5 及其後續版本支援在 CSS 中使用 expression,用途是把某個 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;
}

這個方塊會永遠貼在視窗右下角,不需要監聽 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>

如果只是三五個連結還看不出差別,但當頁面上有幾十上百個連結時,難道還要機械式地複製貼上?改用 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 只是任意自訂的屬性名稱,叫什麼都可以;括號內放的是 JavaScript。別忘了自訂屬性與 expression 之間要有一個冒號,而整段程式必須寫在 style 標籤裡,因為它本質上仍是 CSS 宣告。

一個容易踩到的坑

如果你的特效是「改變 CSS 屬性本身」,直覺寫法會出錯。例如想讓輸入框在滑鼠移入時變紅:

<style type="text/css">
input { star: expression(onmouseover=this.style.backgroundColor="#FF0000";
                        onmouseout=this.style.backgroundColor="#FFFFFF") }
</style>

執行結果是腳本錯誤。正確做法是把樣式操作包進函式裡:

<style type="text/css">
input {
  star: expression(
    onmouseover = function() { this.style.backgroundColor = "#FF0000" },
    onmouseout  = function() { this.style.backgroundColor = "#FFFFFF" }
  )
}
</style>

實戰:批次替換圖片

我們可以為一整批同類物件定義同一份 class 樣式,但如何統一它們的「事件」?假設頁面上有無數個 <img src="xx.jpg">,希望滑鼠移過時 src 換成 xx_over.jpg,用 expression 可以一次搞定:

/* 替換圖片 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;
      }
    }
  )
}

移入時把原路徑暫存到自訂屬性,再換成 hover 版本並打個記號;移出時依記號還原。邏輯不複雜,但能省下大量重複的 HTML 屬性。

使用提醒

並非必要,一般不建議使用 expression。原因是它會被反覆求值,對瀏覽器資源的要求偏高,頁面元素一多就容易拖慢效能。它是一個時代產物,理解原理有助於讀懂舊專案,但新專案請優先考慮 CSS 動畫、transition 或標準的事件綁定方式。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved