CSS expression使用簡介

來源:互聯網
上載者:User
定義 
IE5及其以後版本支援在CSS中使用expression,用來把CSS屬性和Javas cript運算式關聯起來,這裡的CSS屬性可以是元素固有的屬性,也可以是自訂屬性。就是說CSS屬性後面可以是一段Javas cript運算式,CSS屬性的值等於Javas cript運算式計算的結果。 在運算式中可以直接引用元素自身的屬性和方法,也可以使用其他瀏覽器對象。這個運算式就好像是在這個元素的一個成員函數中一樣。

  給元素固有屬性賦值

  例如,你可以依照瀏覽器的大小來安置一個元素的位置。

#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的優勢,但如果你的頁面上有幾十甚至上百個連結,這時的你難道還會機械式地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指令碼,在自訂屬性與expression之間可別忘了還有一個引號,因為實質還是CSS,所以放在style標籤內,而非s cript內。OK,這樣就很容易地用一句話實現了頁面中的連結虛線框的消除。不過你先別得意,如果觸發的特效是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=this.style.backgroundColor="#FF0000";
onmouseout=this.style.backgroundColor="#FFFFFF")}
</style>
<input type="text">
<input type="text">
<input type="text">

  可結果卻是出現指令碼出錯,正確的寫法應該把CSS樣式的定義寫進函數內,如下所示:

<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,因為expression對瀏覽器資源要求比較高。

摘自: http://www.iwms.net/n1838c40.aspx

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.