2011-08-23 29 views
3

爲什麼在下面的代碼不會removeAttribute()刪除任何東西:的removeAttribute()不工作DOM

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>test</title> 
</head> 
<body> 
    <div id="myDiv"> 
     Element with style. 
    </div> 
    <br /> 
    <br /> 
    <button onclick="DelStyle()"> 
     Remove the style attribute from the element 
    </button> 
    <script type="text/javascript"> 
     function DelStyle() { 
      var div = document.getElementById("myDiv"); 
      console.log(div) 
      div.style.border = 'solid #3B3B3D 1px'; 
      console.log(div) 
      div.removeAttribute("style"); 
      console.log(div) 
     } 
    </script> 
</body> 
</html> 
+0

在'div.style.border = '#實1px的3B3B3D';'你不設置元素的樣式*屬性*,你只設置該對象的樣式*屬性*。 – arnaud576875

+0

從@ arnaud576875的評論繼,您可以用'setAttribute'然後'removeAttribute'將工作:http://jsfiddle.net/interdream/tFxMm/1/ –

回答

2

問題是您在DOM更新之前立即進行所有這些更改。相反,考慮實際設置的風格屬性,沒有看到here

 div.setAttribute("style",""); 
1

它看起來像它需要更多的時間,example

function DelStyle() { 
    var div = document.getElementById("myDiv"); 
    console.log(div) 
    div.style.border = 'solid #3B3B3D 1px'; 
    console.log(div) 
    setTimeout((function(div) { 
     return function() { 
      div.removeAttribute("style"); 
      console.log(div); 
     } 
    })(div), 500); 

} 

我半秒後去除屬性。

+0

哈哈,它的實際工作! – AlaskaKid

+0

使用超時並不是最好的方法,也不會是最快的。 –

+0

@Joseph,不,但它表明爲什麼removeAttribute不起作用。 – Joe

4

的removeAttribute( 「風格」)之前,只需撥打的getAttribute( 「風格」)。

例如

function DelStyle() { 
     var div = document.getElementById("myDiv"); 
     console.log(div) 
     div.style.border = 'solid #3B3B3D 1px'; 
     console.log(div) 
     div.getAttribute("style"); 
     div.removeAttribute("style"); 
     console.log(div) 
    } 

http://jsfiddle.net/qTv22/

這看起來很像一個瀏覽器JS優化的bug。雖然HTML5規範說

風格IDL屬性必須返回的CSSStyleDeclaration其值 表示屬性所規定的聲明,如果存在的話。 突變CSSStyleDeclaration對象必須在元素上創建一個樣式屬性 (如果還沒有的話),然後將其值 更改爲表示CSS351CCSSStyleDeclaration對象的序列化形式的值。每個 時間必須返回相同的對象。

Chrome嘗試推遲style屬性的創建,只要它可以,以便IDL屬性的一系列突變可以彙總爲內容屬性的單個創建/更改。代碼簡單地省略在removeAttribute調用之前執行創建/更改操作,但對getAttribute正確執行。內容屬性創建後,removeAttribute將成功銷燬它。

2

由於advised on MDN,應該使用過的removeAttribute設置爲空或空字符串。

它可能無法雖然正常工作,解決的辦法是,如果你想目標不支持英國皇家空軍的不太標準的瀏覽器使用requestAnimationFrame或setInterval的。

0

在撥打removeAttribute()之前,我曾嘗試撥打setAttribute()getAttribute()的方法。

它沒有爲我工作:無論是沒有設置樣式屬性不了了之。

什麼做的工作是使用removeAttributeNode()方法。

如這裏描述:http://www.w3schools.com/jsref/met_element_removeattributenode.asp結果將是相同的;例如

function DelStyle() { 
    var div = document.getElementById("myDiv"); 
    console.log(div) 
    div.style.border = 'solid #3B3B3D 1px'; 
    console.log(div) 
    div.removeAttributeNode(div.getAttribute("style")); 
    console.log(div) 
} 
0

測試此

div.attributes.removeNamedItem("style");