2012-02-25 51 views
-1

我寫一個函數要設置或獲取樣式屬性值:如何創建一個函數來設置或獲取樣式屬性值?

function $(ID){return document.getElementById(ID);} 

Object.prototype.css=function(style,value){ 
    if(value==undefined){ 
     return eval("this.style."+style); 
    } 
    else{ 
     if(isNaN(value)){ 
      return eval("this.style."+style+"=\""+value+"\""); 
     } 
     else{ 
      return eval("this.style."+style+"="+value); 
     } 
    } 
} 

function ad(){ 
    $("ad_ol").css("top","-170px"); 
} 

它可以在Firefox,Chrome和IE9很好地工作,但在IE7和IE8無法正常工作,錯誤消息是:對象不支持「css」屬性或方法

誰能幫幫我?是「這個」問題?是否有更好的功能可以做到這一點?

+5

因爲元素不是實際對象在IE <9無論如何,你的代碼是完全氣餒項目('eval','Object.prototype')。我建議通過最新的最佳實踐來獲取最新信息。 – pimvdb 2012-02-25 13:24:53

+2

「充滿令人沮喪的方面」+1不要使用'eval()',我不會[爲每個'object'附加一個'.css()'方法](http://jsfiddle.net/c5yr3/ )。 – 2012-02-25 13:27:36

+1

或者可以說更糟:http://jsfiddle.net/c5yr3/1/。 – pimvdb 2012-02-25 13:32:13

回答

1

不需要eval,並且你的代碼還有其他缺陷。
嘗試使用類似:

function css(prop,value){ 
    value = value || ''; 

    if(prop) { 
    this.style[prop] = value; 
    return this.style[prop]; 
    } 
    return true; 
} 

function $(ID){ 
    var element = document.getElementById(ID || 'nodId'); 

    if(element) { 
    element.css = css; // create css method for this element 
    } 

    return element; // Note: element is null if no ID was provided 
} 

$("ad_ol").css("top","-170px"); //=> should work now 
+0

我嘗試了一個稍微不同的方法:http://jsfiddle.net/c5yr3/4/ – 2012-02-25 13:38:44

+0

@Jared:是的,那是另一種可能性。有很多通往羅馬的道路。無論如何,無論如何,如果找不到元素,就會拋出錯誤。 – KooiInc 2012-02-25 13:47:56

+0

[也許](http://jsfiddle.net/c5yr3/6/)? – 2012-02-25 13:56:24

相關問題