动画颜色变化的优雅方式

Elegant way to animate color change

本文关键字:方式 颜色 变化 动画      更新时间:2023-09-26

>我有 3 个选项卡,应该有不同的背景和文本颜色。我用这种样式在 CSS 中创建了 3 个类(collor-pallet-1、2、3)。我目前正在做这件丑陋的事情,它也不能顺利地工作。肯定有更好的方法吗?谢谢

$("#tab1").click(function() {
    $(".resp-tab-content").addClass("color-pallet-1");
    if ($(".resp-tab-content").hasClass("color-pallet-2")) {
        $(".resp-tab-content").removeClass("color-pallet-2", 500);
    }
    if ($(".resp-tab-content").hasClass("color-pallet-3")) {
        $(".resp-tab-content").removeClass("color-pallet-3", 500)
    }
    $(".tab-background").css("background-color", function() {
        return $(".resp-tab-content").css("background-color");
        console.log($(".resp-tab-content").css("background-color"));
    });
});
$("#tab2").click(function() {
    $(".resp-tab-content").addClass("color-pallet-2");
    if ($(".resp-tab-content").hasClass("color-pallet-1")) {
        $(".resp-tab-content").removeClass("color-pallet-1", 500);
    }
    if ($(".resp-tab-content").hasClass("color-pallet-3")) {
        $(".resp-tab-content").removeClass("color-pallet-3", 500);
    }
    $(".tab-background").css("background-color", function() {
        return $(".resp-tab-content").css("background-color");
        console.log($(".resp-tab-content").css("background-color"));
    });
});
$("#tab3").click(function() {
     $(".resp-tab-content").addClass("color-pallet-3");
     if ($(".resp-tab-content").hasClass("color-pallet-2")) {
         $(".resp-tab-content").removeClass("color-pallet-2", 500);
     }
     if ($(".resp-tab-content").hasClass("color-pallet-1")) {
         $(".resp-tab-content").removeClass("color-pallet-1", 500);
     }
     $(".tab-background").css("background-color", function() {
         return $(".resp-tab-content").css("background-color");
         console.log($(".resp-tab-content").css("background-color"));
     });
});

看起来您正在尝试为.removeClass()提供一个时间参数,但是当您考虑它时,元素要么有类,要么没有类,没有转换。幸运的是,使用 CSS3,您不需要 JavaScript 来制作颜色动画!若要完成平滑过渡,请为基类(类似于 .tab)提供类似 transition: background-color 0.5s ease; 的规则(带有适当的浏览器前缀)和起始颜色。为调色板类指定要过渡到的颜色。然后,您可以使用一些简单的javascript来切换调色板类名。 CSS Tricks(像往常一样)有一篇关于CSS3转换的有用文章:http://css-tricks.com/almanac/properties/t/transition/。

试试这个插件

https://github.com/jquery/jquery-color

彩色动画示例代码

jQuery("#go").click(function(){
   jQuery("#block").animate({
        backgroundColor: "#abcdef"
   }, 1500 );
});