javascript颜色变化 [英] javascript color change

查看:63
本文介绍了javascript颜色变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!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> 







以上代码无法正常工作点击



i尝试了许多不同的颜色



x.style.color不接受其他区块



else阻止不工作



请帮助




above code not working second time Click

i tried with many different colors

x.style.color not accepting in else block

else block not working

please help

推荐答案

这里解决了这个问题:http://jsbin.com/qusawaro/3/ [ ^ ]



[请接受/投票给您的答案或解决方案以鼓励参与]
This is solved here: http://jsbin.com/qusawaro/3/[^]

[Please accept/up-vote answers or solutions that work for you to encourage participation]


此代码有三个问题。



1)你在if语句中的比较, if(x.style.color =#000000),不是比较而是分配,你缺少一个=使其成为一个比较。基本上发生的是color属性将获得一个赋值,然后在if语句中测试该赋值的结果(值本身),所以它始终为真。

2)设置后 x.style.color #000000 ,颜色不是#000000 而是 rgb(0,0,0)(这里的空格很重要)

3)最初的颜色不是设置,所以x.style.color不返回任何内容。它确实变成了红色,因为if语句有缺陷。



所以为了使代码有效,你会得到这样的东西:

There are three issues with this code.

1) Your comparison in the if statement, if (x.style.color="#000000"), is not a comparison but an assignment, you're missing one = to make it a comparison. What basically happens is that the color property would get a value assigned, and then the result of that assignment (the value itself) is tested in the if statement, so it's always true.
2) After setting x.style.color to #000000, the color is not #000000 but rather rgb(0, 0, 0) (even the spaces are important here)
3) Initially the color is not set, so x.style.color doesn't return anything. It did turn red, because of the flawed if statement.

So to make the code work, you'll get something like this:
function myFunction()
{
    x=document.getElementById("demo") 
    if (!x.style.color || x.style.color=='rgb(0, 0, 0)')
    {
        x.style.color="#FF0000";
    }
    else
    {
        x.style.color="#000000";
    }
}


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



var demoColors = [#000000,#FF0000];

var demoFlag = true;

函数myFunction()

{

var demo = document.getElementById(demo);

demo.style.color = demoColors [+ demoFlag]

demoFlag =!demoFlag;

}
Different browsers return different values for the same colors. You better use different logic to toggle the colors. What I suggest, using pure JavaScript, is this:

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


这篇关于javascript颜色变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆