我有 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 Easy;
的规则(带有适当的浏览器前缀)和起始颜色。为您的调色板类指定您想要过渡到的颜色。然后,您可以使用一些简单的 JavaScript 来切换调色板类名。 CSS Tricks(像往常一样)在这里有一篇关于 CSS3 过渡的有用文章:http://css-tricks.com/almanac/properties/t/transition/ 。
关于javascript - 优雅的颜色变化动画方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049466/