开发者

If statement with background colors

Okay, I've been trying to get this for almost 4 hours now, and it just won't work.

I have a link:

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

And I have a div:

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

I am trying to make a script so the link toggles the background color of the div from transparent to red and back again when you click it again.

This is the code I have:

$(function() {
    $('#framecover').css('backgroundColor', "transparent")
    var framecover = '#framecover'
    $("a#togglecolor").click(function(){
        if ($(framecover).css('backgroundColor') =开发者_如何学JAVA= "transparent")
        {
            $(framecover).animate({ backgroundColor: "red" }, "slow");
        }
        else
        {
            $(framecover).animate({ backgroundColor: "transparent" }, "slow");
        }
    });
});

Through my testing, I've been able to narrow down to where the problem is. It's on this line: if ($(framecover).css('backgroundColor') == "transparent")

Undoubtedly, he problem is above code is the wrong syntax for "if framecover's background-color is transparent". The problem is that I have no clue what the syntax is and I've been scouring the internet for two hours looking for the answer and I can't find it.

Note: I do have the jquery color plugin. This code: $(framecover).animate({ backgroundColor: "red" }, "slow"); works fine. It's the if statement that's giving me trouble.


Assuming you want it to start at transparent (if not just switch them):

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


First this I'd try is to use console.log($('#framecover').css('backgroundColor')) to find out exactly what the background color is at the point of the test (might be none). Copy this and it should work.

Second option, check if the background is red, make the transparent background setting part of the else execution


Have you tried :

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

Works in Chrome but I haven't tried all browsers.

jsFiddle here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜