所以這裡並不特別介紹,因為怎麼寫也沒有比別人寫得好,
因此我主要的目的是應用的分享,所謂師傅領進門,修行靠個人,
這篇就是把小弟個人的修行成果做個紀錄,
以後就不定期來更新,
HTML DOM Style 物件擁有很多屬性,
我們可以直接用 element.style[styleProperty] 去存取他們,
偏偏有些舊 IE 時代的程式會這麼寫:
element.style.getAttribute(styleProperty);糟糕的是,其它的 browser 不甩這種寫法,而是要這麼寫
element.style.setAttribute(styleProperty, value);
element.style.getPropertyValue(style-property)更慘的是,新舊參雜的風格時,有大量的程式需要調整、測試,在不動舊程式的情況下,
element.style.setProperty(style-property, value)
我們希望在其他瀏覽器下模擬出 style.get/setAttribute 的行為,
於是我這麼做:
但這卻遇到一個問題,當用 get/set Property 時, propertyName 格式是和 CSS 一樣,if (typeof (CSSStyleDeclaration.prototype.getAttribute) == "undefined") { CSSStyleDeclaration.prototype.getAttribute = function (propName) { return this.getPropertyValue(Me._changePropName(propName)); } } if (typeof (CSSStyleDeclaration.prototype.setAttribute) == "undefined") { CSSStyleDeclaration.prototype.setAttribute = function (propName, value) { this.setProperty(Me._changePropName(propName), value); } }
中間用 "-" 分隔,但 IE get/set Attribute 的寫法則是第二個字的字首字母大寫(ex: backgroundColor Vs. background-color),所以我們需要處理一下 propName,
處理的方式則用運用 RE 來處理:
function changePropName(propName) { var pattern = /[A-Z]/; var c = ("-" + (propName.match(pattern))).toLowerCase(); var s = propName.split(pattern); var result = s[0]; if (s.length > 1) { result += c + s[1]; } return result; }
利用 RE 找出字串中的大寫字元,以 backgroundColor為例
mach 會找出 C
split 則會找出 background,olor
然後就把 'background' + '-' + 'c' + 'olor' 就完成了我們要的轉換了。
沒有留言 :
張貼留言