JavaScript颜色更改不工作

czfnxgou  于 2023-10-14  发布在  Java
关注(0)|答案(7)|浏览(104)
<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<p id="demo">
JavaScript can change the style of an HTML element.
</p>

<script>
function myFunction()
{ 
  x=document.getElementById("demo") 
  if (x.style.color="#000000")
  {
    x.style.color="#FF0000"; 
    //alert(x.style.color);
  }
  else
  {
    x.style.color="#000000"; 
    //alert(x.style.color);
  }
}
</script>

<button type="button" onclick="myFunction()">Click Me!</button>

</body>
</html>

上面的代码第二次不工作点击
我尝试了许多不同的颜色
x.style.color在else块中不接受
否则块不工作
请帮

gxwragnw

gxwragnw1#

A)在if条件语句中使用==而不是=
B)检查 rgb 颜色符号,而不是十六进制

function myFunction() {

    x = document.getElementById("demo");
    if (x.style.color == "rgb(0, 0, 0)") {
        x.style.color = "#FF0000";
    } else {

        x.style.color = "#000000";
    }
}

http://jsfiddle.net/4QUWq/1/

fbcarpbf

fbcarpbf2#

不同的浏览器可能会为相同的颜色返回不同的值。你最好使用不同的逻辑来切换颜色。我的建议是,使用纯JavaScript:

var demoColors = ["#000000", "#FF0000"];
var demoFlag = true;
function myFunction()
{ 
    var demo = document.getElementById("demo");
    demo.style.color = demoColors[+demoFlag]
    demoFlag = !demoFlag;
}

Live test case

eqqqjvef

eqqqjvef3#

当我在Chrome中测试时,颜色是rgb(255,0,0),这就是为什么if条件总是为false。而你在if中赋值而不是比较(= vs ==)看看:Javascript - Converting colors (numbers -> strings) vice versa

x6h2sr28

x6h2sr284#

当执行比较时,例如在条件中使用==而不是==是赋值运算符。更改比较运算符后,必须使用rgb而不是颜色代码。

function myFunction()
{ 
  x=document.getElementById("demo");
  if (x.style.color=="rgb(0, 0, 0)")
  {
    x.style.color="#FF0000"; 
    //alert(x.style.color);
  }
  else
  {
    x.style.color="#000000"; 
  }
}
ycl3bljg

ycl3bljg5#

使用rgb颜色表示法代替十六进制

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

 <p id="demo">
 JavaScript can change the style of an HTML element.
 </p>

 <script>
 function myFunction() {

 x = document.getElementById("demo");
 if (x.style.color == "rgb(0, 0, 0)") {
    x.style.color = "#FF0000";
   } 
  else {

    x.style.color = "#000000";
 }
}
</script>

<button type="button" onclick="myFunction()">Click Me!</button>

</body>
</html>
mrwjdhj3

mrwjdhj36#

使用style.backgroundColor
它返回颜色或RGB格式的名称,因此您必须转换它。

t5zmwmid

t5zmwmid7#

const counter = document.querySelector('#counter')
const btns = document.querySelectorAll('.btn')

let count = 0

btns.forEach((btn) => {
    btn.addEventListener('click' ,(e) => {
         const styles = e.currentTarget.classList

    if (styles.contains('increase')) {
        count++
    }else if (styles.contains('decrease')) {
        count--
    } else {
        count=0
    }
    //section 01
    if (count>0 ) {
        counter.style.color == "red"
    }
    //section 02
    if (count < 0 ) {
        counter.style.color = "#ff0000"
    } 
    //section 03
    if (count === 0) {
        counter.style.color == "red"
    }

    counter.textContent = count
 })
})

相关问题