【问题标题】:cannot change <label> text color无法更改 <label> 文本颜色
【发布时间】:2012-03-25 16:49:56
【问题描述】:

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

   "style --    Sets or returns the style attribute of an element"

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

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

    <label for="itemImageId" style="color: gray" id="labelForImageUploadID">Item image</label>

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

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

我知道我可以为此标签的文本颜色使用 css 类并使用“className”属性动态 改变上面的css类?你打赌我会的。今晚虽然我抱着这个 DOM 元素的脚 到火。我只有一个“样式”属性要更改(文本颜色)并且不想仅为它添加一个类 -- 我在这里尝试的应该根据文档工作。

我想知道为什么我不能像 DOM 所说的那样使用“style”属性——“get”和“set”DOM 元素的 属性。

在这里我“设置”了我的“样式”属性——这没有任何作用——标签文本保持灰色:

    document.getElementById('labelForImageUploadID').style = "color: rgb(0,0,0)";

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

    document.getElementById('labelForImageUploadID').style = "color: black";

上面的代码执行(在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......)

那么为什么我不能在上面的代码中更改元素的“样式”属性?

【问题讨论】:

    标签: javascript html css dom label


    【解决方案1】:

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


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

    document.getElementById("abc").style.[css property name in camel case] = "[value]";
    

    如果使用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" });
    

    【讨论】:

    • 谢谢蒂姆,大功告成。确实,W3 有点冒险。在您的帮助下,我的标签文本颜色得到了正确响应——也感谢您提供的其他信息。
    【解决方案2】:

    试试这个:

    label { color: red; }
    label span { color: blue; }
    &lt;label&gt; your Labaet &lt;span&gt;Text&lt;/span&gt; &lt;/label&gt;

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      相关资源
      最近更新 更多