开发者

div background opacity change continuously using jquery

开发者 https://www.devze.com 2023-03-24 17:08 出处:网络
I want to change div background opacity to 100% to 0% and again 0% to 100% continuously. How would I go about doing this with jQuery?Here is 开发者_开发问答the markup and CSS I have now.

I want to change div background opacity to 100% to 0% and again 0% to 100% continuously. How would I go about doing this with jQuery? Here is 开发者_开发问答the markup and CSS I have now.

HTML

<div id="sample_div">

</div>

CSS

#sample_div{
    width:300px;
    height:200px;
    background:#65c6ed;
}


You can use jQuery's animate function to do that, or fadeIn and fadeOut which are basically wrappers for it. For example (live copy):

(function() {
    var div = $("selector_for_your_div");

    doFadeIn();

    function doFadeIn() {
        div.fadeIn("slow", doFadeOut);
    }

    function doFadeOut() {
        div.fadeOut("slow", doFadeIn);
    }
})();

You might want to put a termination condition in there, though, because otherwise it keeps going forever and that gets old fast. So for instance (live copy):

(function() {
    var div = $("#target"),
        countdown = 3;

    doFadeIn();

    function doFadeIn() {
        div.fadeIn("slow", doFadeOut);
    }

    function doFadeOut() {
        if (--countdown >= 0) {
            div.fadeOut("slow", doFadeIn);
        }
    }
})();

Update: You've said below you want to animate the background color. It's the same principle as the above, but jQuery on its own can't animate colors. There's a color plug-in that may be able to do it (I haven't tried), and jQuery UI extends animate to do it as well. For example (live copy):

(function() {
    var div = $("#target");

    doFadeIn();

    function doFadeIn() {
      div.animate({
        backgroundColor: "#eeeeee"
      }, "slow", doFadeOut);
    }

    function doFadeOut() {
        div.animate({
        backgroundColor: "#ffffff"
      }, "slow", doFadeIn);
    }
})();

Or with the counter (live copy):

(function() {
    var div = $("#target"),
        counter = 3;

    doFadeIn();

    function doFadeIn() {
      div.animate({
        backgroundColor: "#eeeeee"
      }, "slow", doFadeOut);
    }

    function doFadeOut() {
      if (--counter >= 0) {
        div.animate({
          backgroundColor: "#ffffff"
        }, "slow", doFadeIn);
      }
    }
})();
0

精彩评论

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