【问题标题】:If statement with background colors带有背景颜色的 if 语句
【发布时间】:2011-09-28 07:04:13
【问题描述】:

好的,我已经尝试了将近 4 个小时了,但它就是行不通。

我有一个链接:

<a id="togglecolor" href="#" onclick="ToggleCover();">
    Click here to toggle DIV so you can see what I did.
</a>

我有一个 div:

<div id="framecover" style="position:absolute; width:97%; height:500px; z-index:100; background-color: transparent;">
</div>

我正在尝试制作一个脚本,以便该链接将 div 的背景颜色从透明切换为红色,并在您再次单击它时再次切换回来。

这是我的代码:

$(function() {
    $('#framecover').css('backgroundColor', "transparent")
    var framecover = '#framecover'
    $("a#togglecolor").click(function(){
        if ($(framecover).css('backgroundColor') == "transparent")
        {
            $(framecover).animate({ backgroundColor: "red" }, "slow");
        }
        else
        {
            $(framecover).animate({ backgroundColor: "transparent" }, "slow");
        }
    });
});

通过我的测试,我已经能够缩小到问题所在。在这条线上:if ($(framecover).css('backgroundColor') == "transparent")

毫无疑问,他的问题是上面的代码是“如果 framecover 的背景颜色是透明的”的错误语法。问题是我不知道语法是什么,我已经在互联网上搜索了两个小时寻找答案,但我找不到它。

注意:我有 jquery color 插件。此代码:$(framecover).animate({ backgroundColor: "red" }, "slow"); 工作正常。给我带来麻烦的是 if 语句。

【问题讨论】:

    标签: javascript jquery colors transition


    【解决方案1】:

    假设您希望它以透明开始(如果不只是切换它们):

    $("a#togglecolor").toggle(function(){
         $(framecover).animate({ backgroundColor: "red" }, "slow");
    }, function(){
         $(framecover).animate({ backgroundColor: "transparent" }, "slow");
    });
    

    【讨论】:

    • 我在三个小时前第一次尝试过。那个时候没用,不过后来进步很大,我再试试
    • @MarkKramer 如果问题可能是另一个问题,它会顺利进行
    • 是的,我让它工作了,我只需要先定义颜色和变量,然后将它们全部放入一个函数中。
    【解决方案2】:

    首先,我尝试使用console.log($('#framecover').css('backgroundColor')) 来准确找出测试时的背景颜色(可能没有)。复制这个,它应该可以工作。

    第二个选项,检查背景是否为红色,将透明背景设置为else执行的一部分

    【讨论】:

    • 我使用 alert 来查找它,它告诉我背景颜色是 rgb(0,0,0) 但这不起作用。
    • 背景是 rgba(0 ,0 , 0, 0)。 “rgba”,而不是“rgb”。 alpha 提供透明度。
    • 对不起,我就是这个意思,我试过了,没用
    【解决方案3】:

    你试过了吗:

    if (... .css("backgroundColor") == "rgba(0 ,0 , 0, 0)") { ...
    

    在 Chrome 中工作,但我没有尝试过所有浏览器。

    jsFiddle here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 2021-02-13
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多