Javascript 单击后更改颜色

Javascript 单击后更改颜色,javascript,colors,styles,Javascript,Colors,Styles,我正在尝试使用.style.color更改元素的颜色,但进展不是很顺利。我的目标是让它在点击时先变红再变蓝。有什么建议吗 var turns = 0; function dot_01() { if (turns === 0) { turns++; document.getElementById("dot_01").style.color = 'red'; } else if (turns === 1) { turns--;

我正在尝试使用.style.color更改元素的颜色,但进展不是很顺利。我的目标是让它在点击时先变红再变蓝。有什么建议吗

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>
要使用.style.backgroundColor更改按钮颜色。颜色将更改字体颜色


如果要更改背景色,请按以下方式尝试style.backgroundColor:

document.getElementByIddot_01.style.backgroundColor='red'; 函数dot_01el{ 如果el.style.backgroundColor==‘红色’{ el.style.backgroundColor='蓝色'; } else el.style.backgroundColor='红色'; }
Container我用它来改变样式,它是一个非常简单的JavaScript,可以改变CSS的显示和高度属性来显示/隐藏容器。 很抱歉,我尚未将其更改为您想要的结果,但我希望这会有所帮助,只需通过执行以下操作来修改它以更改颜色:

样式=颜色:红色


顺利对你来说意味着什么?这不可能重复标记为标题的第一个搜索结果的重复,因为它完美地解决了OP的问题。问题,任何缩短它而不是说document.getElementbyId的方法,我知道你可以使用变量,请演示。是的。可以将元素放入变量中。设elm=document.querySelectortestitem;然后您可以与变量elm交互,就好像它是元素一样。elm.style.backgroundColor='ACD';似乎不起作用;/设d1=document.querySelectordot_01;d1.style.backgroundColor='e22b2b';你写的东西对我很合适。我会检查两件事。您的浏览器可能不支持使用let。在这种情况下,您可以将其更改为var,它应该可以工作。如果不起作用,请确保在运行此操作的页面上确实存在ID为d1的元素。
style="color:red";