本文向大家描述一下CSS expression屬性如何將javascript與CSS結合起來,CSS中使用expression可以把CSS屬性和Javas cript表達式關聯起來,也就是說CSS屬性後面可以是一段Javas cript表達式,CSS屬性的值等於Javas cript表達式計算的結果。
CSS expression屬性將javascript與CSS結合起來
關於CSS expression,在51cto.com中有過相關介紹,在IE5及其以後版本支持在CSS中使用expression,用來把CSS屬性和Javas cript表達式關聯起來,這裏的CSS屬性可以是元素固有的屬性,也可以是自定義屬性。就是說CSS屬性後面可以是一段Javas cript表達式,CSS屬性的值等於Javas cript表達式計算的結果。 在表達式中可以直接引用元素自身的屬性和方法,也可以使用其他瀏覽器對象。這個表達式就好像是在這個元素的一個成員函數中一樣。
給元素固有屬性賦值
例如,你可以依照瀏覽器的大小來安置一個元素的位置。
Example Source Code
- #myDiv {
- position: absolute;
- width: 100px;
- height: 100px;
- left: expression(document.body.offsetWidth - 110 + “px”);
- top: expression(document.body.offsetHeight - 110 + “px”);
- background: red;
- }
給元素自定義屬性賦值
例如,消除頁面上的鏈接虛線框。 通常的做法是:
Example Source Code
- <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的做法如下:
Example Source Code
- <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的屬性變化,那麼出來的結果會跟你的本意有差別。例如你想隨鼠標的移進移出而改變頁面中的文本框顏色更改,你可能想當然的會認爲應該寫爲
Example Source Code
- <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樣式的定義寫進函數內,如下所示:
Example Source Code
- <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對瀏覽器資源要求比較高。
◆實例:利用CSS裏expression來實現界面對象的批量控制
問題說明: 用過CSS樣式我們就知道, 可以定義一批對象的class屬性來指定同一個樣式來統一界面. 但如何統一同類型的對象的事件? 比如:界面有無數個 <img src=”**.jpg”> 如何實現鼠標經過此圖片, 圖片的src變成是**_over.jpg?
解決方法: 使用CSS的expression方法。
具體實現要看看.CSS的寫法:
Example Source Code
- /*替換圖片CSS*/
- #imgScript { /*這裏使用對象ID來通配樣式, 也可以定義一個CSS函數*/
- star:expression(
- onmouseover = function()
- {
- /*替換圖片*/
- if(this.hover != null){
- thisthis.name = this.src;
- thisthis.src = this.src.replace(’.jpg’, ‘_over.jpg’);
- this.HasChg = 1;
- }
- },
- onmouseout = function()
- {
- /*還原本來的圖片*/
- if(this.HasChg != null){
- thisthis.src = this.name;
- this.HasChg = null;
- }
- }
- )
- }/*end imgScript*/