Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - Background of DIV needs to change when click on it

How can I do the following:

I have several DIVS

<div style="background-color: black;">text1</div>
<div style="background-color: black;">text2</div>
<div style="background-color: black;">text3</div>
<div style="background-color: black;">text4</div>
<div style="background-color: black;">text5</div>
<div style="background-color: black;">text6</div>

When someone is clicking on the DIV with text5, the background colour needs to change to RED. When that same person is clicking on DIV with text 3, the background colour of text5 need to go back to black en text3 should get the background color to RED. And so on with the other DIVS.

So the background colour needs to change when someone is cliking on another DIV.

Is this possible with a simple javascript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to add classes to the divs in html so that you're able to access them from the javascript along with an onclick so that you can detect when each div has been clicked. From the onclick call a javascript function passing in the current div as a parameter using this.

In the changeColour function (that's getting called from the onclick) in javascript first call a function to set all the divs back to the default colour by getting an array of them all using the document.getElementsByClassName, loop through them and reset the colour.

Once that's done and the code executeion is back in the changeColour function change the colour of the clicked on div (which was passed in as a parameter).

function changeColour(item)
{
    resetColour();
    item.style.backgroundColor = 'red';
}

function resetColour()
{
    var divsToReset = document.getElementsByClassName("colouredDivs");
    for(var i=0; i < divsToReset.length; i++) 
    {
         var div = divsToReset[i];
         div.style.backgroundColor = 'black';
    }
}
<div class="colouredDivs" style="background-color: black;" onClick="changeColour(this);">text1</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text2</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text3</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text4</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text5</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text6</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...