Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to change the background color of 'exampleDiv' from the original white background to when I call the code below to immediate change the background yellow and then fade back to the original white background.

$("#exampleDiv").animate({ backgroundColor: "yellow" }, "fast");

However, this code does not work.

I have only the JQuery core and JQuery UI linked to my web page.

Why doesn't the code above work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
293 views
Welcome To Ask or Share your Answers For Others

1 Answer

I've had varying success with animate, but found that using its built in callback plus jQuery's css seems to work for most cases.

Try this function:

$(document).ready(function () {

    $.fn.animateHighlight = function (highlightColor, duration) {
        var highlightBg = highlightColor || "#FFFF9C";
        var animateMs = duration || "fast"; // edit is here
        var originalBg = this.css("background-color");

        if (!originalBg || originalBg == highlightBg)
            originalBg = "#FFFFFF"; // default to white

        jQuery(this)
            .css("backgroundColor", highlightBg)
            .animate({ backgroundColor: originalBg }, animateMs, null, function () {
                jQuery(this).css("backgroundColor", originalBg); 
            });
    };
});

and call it like so:

$('#exampleDiv').animateHighlight();

Tested in IE9, FF4, and Chrome, using jQuery 1.5 (do NOT need UI plugin for this). I didn't use the jQuery color plugin either - you would only need that if you want to use named colors (e.g. 'yellow' instead of '#FFFF9C').


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...