深度剖析CSS2.0中的expression應(yīng)用
你對(duì)CSS2.0中的expression應(yīng)用是否了解,這里和大家分享一下,IE5及其以后版本支持在CSS中使用expression,CSS屬性后面可以是一段Javascript表達(dá)式,CSS屬性的值等于Javascript表達(dá)式計(jì)算的結(jié)果。
CSS2.0中的expression應(yīng)用
IE5及其以后版本支持在CSS中使用expression,用來把CSS屬性和Javascript表達(dá)式關(guān)聯(lián)起來,這里的CSS屬性可以是元素固有的屬性,也可以是自定義屬性。就是說CSS屬性后面可以是一段Javascript表達(dá)式,CSS屬性的值等于Javascript表達(dá)式計(jì)算的結(jié)果。在表達(dá)式中可以直接引用元素自身的屬性和方法,也可以使用其他瀏覽器對(duì)象。這個(gè)表達(dá)式就好像是在這個(gè)元素的一個(gè)成員函數(shù)中一樣。
給元素固有屬性賦值
例如,你可以依照瀏覽器的大小來安置一個(gè)元素的位置。
ExampleSourceCode
- #myDiv{
- position:absolute;
- width:100px;
- height:100px;
- left:expression(document.body.offsetWidth-110+\"px\");
- top:expression(document.body.offsetHeight-110+\"px\");
- background:red;
- }
給元素自定義屬性賦值
例如,消除頁(yè)面上的鏈接虛線框。通常的做法是:
ExampleSourceCode
- <ahrefahref=\"link1.htm\"onfocus=\"this.blur()\">link1</a>
- <ahrefahref=\"link2.htm\"onfocus=\"this.blur()\">link2</a>
- <ahrefahref=\"link3.htm\"onfocus=\"this.blur()\">link3</a>
粗看或許還體現(xiàn)不出采用expression的優(yōu)勢(shì),但如果你的頁(yè)面上有幾十甚至上百個(gè)鏈接,這時(shí)的你難道還會(huì)機(jī)械式地Ctrl+C,Ctrl+V么,何況兩者一比較,哪個(gè)產(chǎn)生的冗余代碼更多呢?
◆采用expression的做法如下:
ExampleSourceCode
- <styletypestyletype=\"text/css\">
- a{star:expression(onfocus=this.blur)}
- </style>
- <ahrefahref=\"link1.htm\">link1</a>
- <ahrefahref=\"link2.htm\">link2</a>
- <ahrefahref=\"link3.htm\">link3</a>
說明:里面的star就是自己任意定義的屬性,你可以隨自己喜好另外定義,接著包含在expression()里的語(yǔ)句就是JS腳本,在自定義屬性與expression之間可別忘了還有一個(gè)引號(hào),因?yàn)閷?shí)質(zhì)還是CSS,所以放在style標(biāo)簽內(nèi),而非script內(nèi)。OK,這樣就很容易地用一句話實(shí)現(xiàn)了頁(yè)面中的鏈接虛線框的消除。不過你先別得意,如果觸發(fā)的特效是CSS的屬性變化,那么出來的結(jié)果會(huì)跟你的本意有差別。例如你想隨鼠標(biāo)的移進(jìn)移出而改變頁(yè)面中的文本框顏色更改,你可能想當(dāng)然的會(huì)認(rèn)為應(yīng)該寫為:
ExampleSourceCode
- <styletypestyletype=\"text/css\">
- input
- {star:expression(onmouseover=this.style.backgroundColor=\"#FF0000\";
- onmouseout=this.style.backgroundColor=\"#FFFFFF\")}
- </style>
- <styletypestyletype=\"text/css\">
- input{star:expression(onmouseover=this.style.backgroundColor=\"#FF0000\";
- onmouseout=this.style.backgroundColor=\"#FFFFFF\")}
- </style>
- <inputtypeinputtype=\"text\">
- <inputtypeinputtype=\"text\">
- <inputtypeinputtype=\"text\">
可結(jié)果卻是出現(xiàn)腳本出錯(cuò),正確的寫法應(yīng)該把CSS樣式的定義寫進(jìn)函數(shù)內(nèi),如下所示:
ExampleSourceCode
- <styletypestyletype=\"text/css\">
- input{star:expression(onmouseover=function()
- {this.style.backgroundColor=\"#FF0000\"},
- onmouseout=function(){this.style.backgroundColor=\"#FFFFFF\"})}
- </style>
- <inputtypeinputtype=\"text\">
- <inputtypeinputtype=\"text\">
- <inputtypeinputtype=\"text\">
注意:不是非常需要,一般不建議使用expression,因?yàn)閑xpression對(duì)瀏覽器資源要求比較高!
【編輯推薦】
- CSS樣式實(shí)時(shí)切換技巧剖析
- CSS中margin邊界疊加問題及解決方案
- CSS樣式表高效使用八大秘訣
- 創(chuàng)建和插入CSS樣式表秘笈
- 實(shí)現(xiàn)CSS垂直居中的五大方法及優(yōu)缺點(diǎn)