1

リンクがクリックされたときに要素の内部 HTML を変更する単純な JavaScript を取得しました。次のようになります。

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

}

の CSSheaderは次のとおりです。

#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私の問題は、押されたリンクに応じて要素の背景色を変えたいということです。最初のリンクの背景は赤、2 番目のリンクは青、3 番目のリンクは緑などになります。

JavaScript を使用して既存の CSS ID にプロパティを追加するにはどうすればよいですか? 私は jQuery を使用しないので、純粋な JavaScript のみを使用してください :)

4

4 に答える 4

12

styleプロパティを使用できます

document.getElementById("header").style.backgroundColor = 'red';
于 2012-10-29T13:14:06.057 に答える
1

アプローチを少し変更できます。

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;
}​
于 2012-10-29T13:15:54.103 に答える
0

ID に追加のプロパティを追加する必要はありません。要素にインライン スタイリングを追加するか、インライン スタイリングを使用したくない場合は、代わりに追加のクラスを要素に追加して、適切な背景色。

jQuery を使用せずに要素からクラスを追加/削除する方法の例を次に示します: http://snipplr.com/view/3561/addclass-removeclass-hasclass/

于 2012-10-29T13:14:17.770 に答える
0

See sample code in this page : 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>​
于 2012-10-29T13:21:54.710 に答える