今天在寫js獲取style樣式的時候遇到了一個小問題,即用以下的代碼獲取不到id為“qqChat”div的一些樣式:
function $(id){ return documentElementById(id); } var qL = $("qqChat").style.left; alert(qL);//結果為空
仔細檢查代碼,div框的top,left值也定義了啊,為什么就獲取不到呢?隨搜索之。終於發現了問題所在:
js只能修改html內部的css樣式代碼。
在JavaScript中,通過document.getElementById(id).style.XXX可以獲取到XXX的值,但意外的是這樣做只能取到通過內嵌方式設置的樣式值,即style屬性里面設置的值。
原來是我把樣式寫到了head中。但是一般不把樣式寫成行內樣式的,所以得找到解決的辦法。隨繼續尋找之。功夫不負有心人,終於找到了解決方法:
如果是ie,問題很好解決,只要把style改成currentStyle即可。即:
function $(id){ return documentElementById(id); } var qL = $("qqChat").currentStyle.left; alert(qL);//結果有值
而在firefox下,則采用另外一種方式:
function $(id){ return documentElementById(id); } var qL = document.defaultView.getComputedStyle($("qqChat"),null) var qLL = qL.left; alert(qLL);//結果有值
綜合IE和Firefox之后解決辦法如下:
function $(id) { return document.getElementById(id); } function checkStyle(o){ if(o.currentStyle){ var cur = o.currentStyle; }else{ var cur = document.defaultView.getComputedStyle(o, null); } return cur; } var one = checkStyle($("qqChat")); alert(one.left);//有值
轉自:http://www.17leba.com