jQuery animate()不适用于If-Else语句

时间:2017-04-13 23:52:34

标签: javascript jquery

JQuery初学者在这里。当我点击它们时,我正试图让一组div从红色变为蓝色。当我再次点击它们时,我希望div变回红色。我尝试使用jQuery的animate()方法(使用jQuery颜色插件)来改变div的颜色。但是,以下代码仅部分有效。

$(document).ready(function(){

    $("div").click(function() {
        $("div").each(function() {
            if (this.style.color !== "blue") {
                $(this).animate({   
                    color:'blue'
                },1000);
            } else {
                this.style.color = "red";
            }
        });
    }); 
});

当我单击div时,if语句正常工作。 div变为蓝色。但是,当我再次单击div时,div不会变回红色。 else语句似乎不起作用。关于我的错误的任何想法?当我用$(this).animate({...})替换this.style.color = "blue";时,else语句有效,所以我认为我在使用animate()方法做错了。

这是HTML文件

<!DOCTYPE html> 
<html> 
<head> 
    <title> each() test1 </title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
     <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <style>
    body{
        background-color: #000000;
        color: #ffffff;
    }
    div {
        font-size: 3em;
        color: #ff0000;
        text-align: center;
        cursor:pointer;
        font-weight: bolder;
        width: 300px;
    }
    </style> 
</head> 
<body> 
    <div> Click here </div> 
    <div> to iterate through </div> 
    <div> these divs </div> 
</body>
<script src="theJavaScriptFile.js"> </script> 
</html> 

2 个答案:

答案 0 :(得分:1)

不要使用bluered颜色代码。它将转换为RGB代码。 例如,this.style.colorRGB(0,0,255)而不是blue,因此无论颜色是什么,您的表达式始终会返回true

我以不同的颜色模式创建此示例,以便您查看https://jsfiddle.net/3tpncgr1/1/

无论如何,如果你想要特定颜色的特殊逻辑,那么继续使用这种方法。否则,使用类名而不是颜色代码来确定。因为浏览器始终会为rgb属性

返回color

答案 1 :(得分:0)

我会通过使用活动类来控制状态来管理它。

在这种情况下,我会成功改变

&#13;
&#13;
{-# LANGUAGE RankNTypes #-}
data X = Y Integer
       | Z Double
wrap :: (forall n. Num n => n -> n) -> X -> X
wrap f (Y i) = Y $ f i
wrap f (Z i) = Z $ f i
&#13;
$(document).ready(function(){

    $("div").click(function() {
       $.each( $(this).parent().children("div"),function() {
            if (!$(this).hasClass('active')) {
              $(this).addClass('active');
                $(this).animate({   
                    color:'blue'
                },1000);
            } else {
              $(this).removeClass('active');
                this.style.color = "red";
            }
        });
    }); 
});
&#13;
&#13;
&#13;

相关问题