JQuery background color animate not working

前端 未结 9 1880
温柔的废话
温柔的废话 2020-12-10 05:27

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 f

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 05:53

    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').

提交回复
热议问题