admin管理员组

文章数量:1391747

I am trying to change the color of an element using .style.color and it isn't going very smoothly. My goal is for it to change red and then blue on clicks. Any remendations?

var turns = 0;

function dot_01() {
    if (turns === 0) {
        turns++;
        document.getElementById("dot_01").style.color = 'red';
     } else if (turns === 1) {
        turns--;
        document.getElementById("dot_01").style.color = 'blue';
    }
}

<div class="dot" id="dot_01" onclick="dot_01()"></div>

I am trying to change the color of an element using .style.color and it isn't going very smoothly. My goal is for it to change red and then blue on clicks. Any remendations?

var turns = 0;

function dot_01() {
    if (turns === 0) {
        turns++;
        document.getElementById("dot_01").style.color = 'red';
     } else if (turns === 1) {
        turns--;
        document.getElementById("dot_01").style.color = 'blue';
    }
}

<div class="dot" id="dot_01" onclick="dot_01()"></div>
Share Improve this question edited May 15, 2018 at 23:32 Mamun 69k9 gold badges51 silver badges62 bronze badges asked May 15, 2018 at 23:16 BennBenn 551 gold badge1 silver badge8 bronze badges 4
  • what does smoothly mean for you? – user3163101 Commented May 15, 2018 at 23:19
  • it isnt working – Benn Commented May 15, 2018 at 23:19
  • Possible duplicate of Change Button color onClick – user5734311 Commented May 15, 2018 at 23:27
  • Marking this as dupe of the first search result for the title, given that the answer addresses OP's issues perfectly. – user5734311 Commented May 15, 2018 at 23:28
Add a ment  | 

3 Answers 3

Reset to default 1

You want to use .style.backgroundColor to change the button color. .color is going to change the font color.

<input type="button" value="Click Me" onclick="this.style.backgroundColor = '#000'; this.style.color = '#FFF';" />

If you mean to change the background color try style.backgroundColor like the following way:

document.getElementById("dot_01").style.backgroundColor = 'red';
function dot_01(el) {
  if (el.style.backgroundColor === 'red') {
    el.style.backgroundColor = 'blue';   
  }
  else el.style.backgroundColor = 'red';
}
<div class="dot" id="dot_01" onclick="dot_01(this)">Container</div>

I'm using this to change styling, it's a very simple JavaScript that changes the display and height properties of the CSS to show / hide a container. Sorry I haven't changed it to your desired oute yet but I hope this helps, just modify it to change the color by doing something like:

style="color:red"

https://jsfiddle/raydekker/u821a84d/

style="color:red";

本文标签: javascriptChange Color onClickStack Overflow