-1

我正在尝试创建一个通用的“颜色闪烁确认”功能,它将对象的背景闪烁为绿色,然后淡出为现有颜色。

所以我可能有两个元素,我在 click() 上调用它:

li background-color: red
li background-color: black

如果我单击第一个,它会从绿色变为红色。如果我单击第一个,它会从绿色变为黑色。

jQuery逻辑:

点击事件:

listItem.each(function(){confirmFlash($(this),$(this).css("backgroundColor"))});

功能:

function confirmFlash(objectToFlash,backgroundColor){
    objectToFlash.css("backgroundColor","#84da9a").animate({opacity: 1}, 1000).animate({backgroundColor: backgroundColor}, 500);
}

这很好用。问题:

如果我还给上面的 LI 一个 :hover state 背景颜色:

li background-color: red
li background-color: black
li:hover background-color: purple

然后我所有的渐变都从绿色变为紫色。这是有道理的,因为在单击 LI 时,背景确实是紫色的。

有没有一种巧妙的方法来获取“非悬停”CSS 类的背景颜色?

改写它的一种方法是,我想获取分配给 LI 当前类的背景颜色,而不是伪类。

还是不是通过 CSS 实现悬停的解决方案,而是通过 jQuery 来实现?

4

3 回答 3

0

这就是我想出的。我从我的 CSS 中省略了 :hover 类并创建了一个 .hover ,然后我通过 jquery 添加或删除它:

function createToggleList(){
    // create mouseovers/outs 
    $("ul.toggleList li").mouseover(function(){
        $(this).addClass("hover");
    });
    $("ul.toggleList li").mouseout(function(){
        $(this).removeClass("hover");
    });     
    // attach the click event
    $("ul.toggleList li").click(function(){toggleToggleListItem($(this))})
};

然后,在点击事件触发的函数中,我删除了 HOVER 类,这样我就可以获取悬停之前的背景:

function toggleToggleListItem(listItem) {
    listItem.removeClass("hover");
    confirmFlash(listItem,listItem.css("backgroundColor"));
};

下面是创建 flash 的函数:

function confirmFlash(objectToFlash,backgroundColor){
    objectToFlash.css("backgroundColor","#84da9a").animate({opacity: 1}, 1000).animate({backgroundColor: backgroundColor}, 500, function(){
        objectToFlash.removeAttr("style");
    });
}

请注意,我必须在动画后删除 STYLE 属性,因为我希望项目再次从 CSS 文件继承,而不是通过动画创建的新内联样式。

那行得通。哇!

于 2009-10-29T22:46:30.237 回答
0

你真的应该安装颜色插件,它可以让你直接为颜色设置动画。动画不透明度是有问题的,因为文本和背景都是动画的。

见: http: //plugins.jquery.com/project/color

于 2009-10-29T21:58:10.827 回答
0

您可以在绑定 confirmFlash 功能时将初始背景颜色存储在变量中,如下所示...

jQuery.fn.confirmFlash = function(config){
    this.each(function() {
        var elem = jQuery(this);

        // Store the starting background color
        var startBg = elem.css("backgroundColor");

        // When the element is clicked
        elem.click(function() {
            // Set the start background color
            elem.css("backgroundColor", startBg);
            // Animate to the "flash" color
            elem.animate({backgroundColor: config.backgroundColor}, {duration: 1000, complete: function() {
                // Animate back to the start background color
                elem.animate({backgroundColor: startBg}, {duration: 1000});
            }});
        });
    });
};

然后你可以像这样使用它......

$("li").confirmFlash({backgroundColor: "#84da9a"});
于 2009-10-29T22:02:34.823 回答