【问题标题】:Adding a property to a CSS id using JavaScript使用 JavaScript 向 CSS id 添加属性
【发布时间】:2012-10-29 13:10:54
【问题描述】:

我有一个简单的 JavaScript,它可以在单击链接时更改元素的内部 HTML,它看起来像这样:

function changeHeader(Index)
{
    var headers = new Array("Coffee tables","Side tables","Stand tables","Dinner tables","Stools","Pedestals");
    document.getElementById("header").innerHTML = headers[Index];

}

header 的 CSS 如下:

#header
{
    cursor: hand; 
    cursor: pointer;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

HTML 基本上是这样的:

<p id="header">Press a link</p>
<a href=# onclick="changeHeader(1)">Coffee tables</a>
<a href=# onclick="changeHeader(2)">Side tables</a>
<a href=# onclick="changeHeader(3)">Stand tables</a>

等等。我的问题是我想在 header 元素上使用不同的背景颜色,具体取决于按下的链接。第一个链接可能是红色背景,第二个是蓝色,第三个是绿色,依此类推..

如何使用 JavaScript 将属性添加到现有的 CSS id?我不使用 jQuery,所以请只使用纯 JavaScript :)

【问题讨论】:

    标签: javascript css class


    【解决方案1】:

    你可以使用style属性

    document.getElementById("header").style.backgroundColor = 'red';
    

    【讨论】:

    • background-color 应该是:backgroundColor
    【解决方案2】:

    你可以稍微改变你的方法:

    function changeHeader(Index) {
        var headers = [
            {color: 'red', text: "Coffee tables"},
            {color: 'blue', text: "Side tables",
            {color: '#DDD', text: "Stand tables"},
            {color: "#ACD12A", text: "Dinner tables"},
            {color: "Chuck Norris", text: "Stools"}
        ];
        var header = document.getElementById("header"),
        header.innerHTML = headers[Index].text;
        header.style.backgroundColor = headers[Index].color;
    }​
    

    【讨论】:

      【解决方案3】:

      您不需要向 ID 添加其他属性,您可以向元素添加内联样式,或者如果您不想使用内联样式,则可以向元素添加额外的类,即设置正确的背景颜色。

      这是一个示例,说明如何在不使用 jQuery 的情况下从元素中添加/删除类:http://snipplr.com/view/3561/addclass-removeclass-hasclass/

      【讨论】:

        【解决方案4】:

        查看本页示例代码:http://jsfiddle.net/Rd4y5/

        js:

        d = document.getElementById("d1");
        console.log(d.style);
        d.style.backgroundColor="red";
        d.style.width = "300px";
        d.style.height="300px";
            console.log(d.style);
        

        html:

        <div id='d1'>a<div>​
        

        【讨论】:

          猜你喜欢
          • 2013-04-06
          • 1970-01-01
          • 1970-01-01
          • 2011-10-26
          • 2021-05-24
          • 1970-01-01
          • 2011-09-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多