JQuery background color animate not working

前端 未结 9 1832
温柔的废话
温柔的废话 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:52

    I had the same problem and I was able to get everything to work when I included the correct js files.

    <script src="/Scripts/jquery-1.9.1.js"></script>
    <script src="/Scripts/jquery-ui-1.8.20.js"></script>
    <script src="/Scripts/jquery.color-2.1.2.js"></script>
    

    I took it a step further and found a nice extension someone wrote.

    jQuery.fn.flash = function (color, duration) {
       var current = this.css('backgroundColor');
       this.animate({ backgroundColor: 'rgb(' + color + ')' }, duration / 2)
       .animate({ backgroundColor: current }, duration / 2);
    }
    

    The above code allows me to do the following:

    $('#someId').flash('255,148,148', 1100);
    

    That code will get your element to flash to red then back to its original color.

    Here's some sample code. http://jsbin.com/iqasaz/2

    0 讨论(0)
  • 2020-12-10 05:52

    Just added this snippet below jquery script and it immediately started working:

    <script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
    

    Source

    0 讨论(0)
  • 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').

    0 讨论(0)
提交回复
热议问题