用Javascript改变div背景颜色

时间:2014-09-16 02:19:52

标签: javascript css

我有照片库。每张照片都放在小div中。 我想在点击照片时生效,使这个div红色并且它已经有效了。 但现在我想再次点击它时红色div颜色变回白色。 这将是某种选择效果 我试图自己改进我的js代码,但我非常糟糕,它不起作用

以下是我的照片在循环中的显示方式

echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" style="background-color:white" onclick="clicked('.$photoid.');"></div>';

这是我的功能

function clicked(photoid){   
    var divcolor = document.getElementById(photoid.toString()).backgroundColor;

    if (divcolor = "white"){
        document.getElementById(photoid.toString()).style.backgroundColor = 'red';
    } else {
        document.getElementById(photoid.toString()).style.backgroundColor = 'white';
    }
}

它变成红色但不变成白色。我该怎么办? 请帮帮我:D

3 个答案:

答案 0 :(得分:1)

有两个问题

1)你在说

var divcolor = document.getElementById(photoid.toString()).backgroundColor;

它应该总是返回undefined

var divcolor = document.getElementById(photoid.toString()).style.backgroundColor;

2)你在说

if (divcolor = "white")

哪个是作业运算符&amp;永远不会返回false,因此它永远不会进入else条件。

if (divcolor == "white")

为了避免这些问题,你应该说

if ("white" == divcolor)

因此,如果您错误地在=处使用==,则会引发语法错误。

答案 1 :(得分:0)

在if语句中进行比较时,您有一个赋值运算符,即您只使用了一个=。要获得相等比较,请使用两个,即==;

divcolor == "white"

看看你正在尝试什么,你可能会更好地使用jQuery代替切换功能。

希望这有帮助。

答案 2 :(得分:0)

您可以利用事件冒泡和this关键字来提高您的代码效率......

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script>
        function clicked(theElement) {
            var divcolor = theElement.style.backgroundColor;

            if (divcolor == "white") {
                theElement.style.backgroundColor = 'red';
            } else {
                theElement.style.backgroundColor = 'white';
            }
        }
    </script>
    <style>
        div {
            height: 200px;
            width: 200px;
            outline: 1px solid green;
        }
    </style>
</head>
<body>
    <div onclick="clicked(this);" style="background-color:white" >
        <img src="http://www.gravatar.com/avatar/d3b62f0eaa6fcaef8d8c76ba9f8a5ea4/?default=&amp;s=160" alt="photo" class="photolink" />
    </div>
</body>
</html>
相关问题