2012-05-23 85 views
2

爲什麼div的背景顏色不更新?bgColor不通過JavaScript更新

Tagger.prototype.mouseDown = function(event) { 
    this.element.style.posLeft = event.clientX; 
    this.element.style.width = 200 + "px"; 
    this.element.style.height = 200 + "px"; 
    this.element.style.position = "absolute"; 
    this.element.style.zIndex = 10; 
    this.element.style.bgColor = "yellow"; 
    console.log(this.element); 
    console.log(this.element.style.bgColor); 
} 

控制檯輸出爲:

<div id="tagbox4" class="tagbox" style="width: 200px; height: 200px; position: absolute; z-index: 10;"> 
yellow 

我可以在瀏覽器中檢查元素選擇div,但它沒有背景色,即使在控制檯說,這是「黃色」。

+0

...再次,我會建議使用庫進行這種操作。在http://api.jquery.com/css/#css2上使用jQuery'.css()'是一件輕而易舉的事 - 最後一個例子 –

+0

CSS中沒有'bgColor' ... –

回答

5

它不是bgColor,這是當CSS不流行時,設置背景顏色的過時方式。

您想要設置CSS屬性background-color。當您使用JavaScript進行設置時,可以刪除短劃線並使用camelCase。所以你想設置backgroundColor。

this.element.style.backgroundColor 
4

css property is backgroundColor的名稱,而不是bgColor

您的控制檯說"yellow",因爲它讀取的bgColor屬性 - 這只是不影響顯示 - 也不包含在您用元素的源記錄的樣式屬性中。