简体   繁体   English

如何重置我的 document.getElementById 颜色值

[英]How can i reset my document.getElementById color value

I'm trying to change the color from red to blue but when the red color come its unchangeable我正在尝试将颜色从红色更改为蓝色,但是当红色变为不变时

var colorvalue=0;
var sizevalue;
function CG()
{
    colorvalue ++;
    if (colorvalue==0)
    {
        document.getElementById("testd").style.color = "blue";
    }
    else if(colorvalue==1)
    {
        document.getElementById("testd").style.color = "red";
    }
    if(colorvalue > 1)
    {
        colorvalue = 0;
    }
}

I already got the answer but how do i have more colors我已经得到了答案,但我如何有更多的颜色

Thanks for seeing my question and if you do thanks for answering感谢您看到我的问题,如果您这样做,感谢您的回答

i edit a bit of your code.我编辑了一些你的代码。 try below试试下面

var colorvalue=0;
var sizevalue;
function CG()
{
    colorvalue ++;
    if (colorvalue % 2 == 0)
    {
        document.getElementById("testd").style.color = "blue";
    }
    else
    {
        document.getElementById("testd").style.color = "red";
    }
}

Used modulo operation: So if there is a remainder of colorvalue , element will be red.使用模运算:所以如果有余数colorvalue ,元素将是红色的。

An alternative method would be to use CSS rather than setting the style directly on the element using JavaScript.另一种方法是使用 CSS,而不是使用 JavaScript 直接在元素上设置样式。

Initialise your text with the color red, and then toggle a blue class on/off using classList .用红色初始化文本,然后使用classList打开/关闭蓝色类

 const test = document.querySelector('.test'); const button = document.querySelector('button'); button.addEventListener('click', handleClick, false); function handleClick() { test.classList.toggle('blue'); }
 .test { color: red; } .blue { color: blue; }
 <p class="test">This is a test</p> <button>Change color</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM