无法更改<label>文本颜色

wan*_*est 5 html javascript css label dom

我对基本HTML DOM元素的研究说明了任何DOM元素的"样式"属性(来自http://www.w3schools.com/jsref/dom_obj_all.asp):

   "style --    Sets or returns the style attribute of an element"
Run Code Online (Sandbox Code Playgroud)

'label'标签是一个dom元素.因此它具有"风格"属性.正如它在上面的w3schools链接中指出的那样,所有dom元素都具有"样式"属性.

事实上,我在这里设置(内联)标签标签的'style'属性- 这很好用:

    <label for="itemImageId" style="color: gray" id="labelForImageUploadID">Item image</label>
Run Code Online (Sandbox Code Playgroud)

页面加载时标签文本颜色为灰色.

在一定条件下(用户已指示他们已准备好选择要上传的图像) - 我需要通过将上面的初始灰色文本颜色更改为黑色来将上传显示为"已启用".

我知道我可以使用css类来处理这个标签的文本颜色,并使用'className'属性动态地改变上面的css类吗?你敢打赌我做.今晚虽然我把这个DOM元素的脚抬起来了.我只需要一个'style'属性来改变(文本颜色)并且不想仅为它添加一个类 - 我在这里尝试的应该根据文档工作.

我想知道为什么我不能使用'style'属性,因为DOM说我可以 - "获取"和"设置"DOM元素的属性.

在这里,我"设置" - 我的"风格"属性 - 这没有 - 标签文本仍为灰色:

    document.getElementById('labelForImageUploadID').style = "color: rgb(0,0,0)";
Run Code Online (Sandbox Code Playgroud)

这也不会将颜色从灰色变为黑色:

    document.getElementById('labelForImageUploadID').style = "color: black";
Run Code Online (Sandbox Code Playgroud)

上述代码在页面上已经显示标签执行(在javascript中),并且响应于表单上按钮的onclick事件,标签也是其中的一部分.

是否存在"设置"DOM元素的"样式"属性的错误?根据http://www.w3schools.com/jsref/dom_obj_all.asp,

   "HTMLElement Object

    The following properties, and methods can be used on all HTML elements."

        (other properties here.....)
   "style --    Sets or returns the style attribute of an element"
       (still other properties here......)
Run Code Online (Sandbox Code Playgroud)

那么为什么我不能在上面的代码中更改元素的'style'属性呢?

Tim*_*ora 8

在2017年查看此答案后,设置整个样式字符串的原始示例可以正常工作.我不知道问题是什么,但下面的例子仍然是有效的方法.


使用JavaScript设置样式通常遵循以下格式:

document.getElementById("abc").style.[css property name in camel case] = "[value]";
Run Code Online (Sandbox Code Playgroud)

如果使用jQuery,它会变得更清晰:

// find all elements with the tag name "bar" that are direct 
// descendants of an element with the class name "foo"
$(".foo > BAR").css("color", "red");

// set multiple properties
$(".foo > BAR").css({ color: "red", "background-color": "beige" });
Run Code Online (Sandbox Code Playgroud)