2

为什么div的背景颜色不更新?

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,但它没有背景颜色,即使控制台说它是“黄色”。

4

2 回答 2

5

它不是 bgColor,这是一种在 CSS 不流行时设置背景颜色的过时方式。

您想设置 CSS 属性background-color。当您使用 JavaScript 设置它时,您删除破折号并使用 camelCase。所以你要设置背景颜色。

this.element.style.backgroundColor
于 2012-05-24T00:00:23.997 回答
4

css 属性的名称是backgroundColor,而不是bgColor

您的控制台说"yellow",因为它读取bgColor属性 - 这不会影响显示 - 并且也不包含在您使用元素源记录的样式属性中。

于 2012-05-24T00:01:02.823 回答