jQuery更改悬停在颜色上,然后返回原始颜色

tec*_*ant 4 javascript css jquery colors hover

我在页面上有一些按钮,其颜色通过jQuery更改,说明哪一个是活动的.我只想在悬停时添加颜色更改,之后它会在离开时返回到原始颜色(由jQuery决定).

我首先使用css:.showlink li:hover {color:#aaa;}除了当切换页面并且jQuery改变颜色时它适当地工作,它超过了CSS.

然后我决定使用简单的jQuery来说明什么东西在徘徊时,改变它的颜色.这不完全有效,因为它会永久改变颜色.为了缓解这种情况,我在函数中添加了一些函数,将函数返回到不同的颜色.

有什么方法可以在悬停时更改之前将其恢复为原始颜色?

// Changes color on hover
    $(function() {
        $('.showlink').hover(function(){
            $(this).css('color', '#aaa');
        },
        function(){
           $(this).css('color', '#f3f3f3');
        });
    });
//Changes color depending on which page is active, fades that page in
    $(function(){
        $('#show_one').css('color', '#ffcb06');
        $('#two, #three').hide();
    });

    $('.showlink').click(function(){
        $('.showlink').css('color', '#f3f3f3');
        $(this).css('color', '#ffcb06');
        var toShow = this.id.substr(5);
        $('div.page:visible').fadeOut(600, function(){
            $('#' + toShow).fadeIn(600);
        });
    });
Run Code Online (Sandbox Code Playgroud)

Wul*_*ulf 7

.showlink li:hover {color:#aaa !important;}
Run Code Online (Sandbox Code Playgroud)

将取代其他一切.


Dav*_*mas 7

我建议使用数组来记录原始颜色值,并在mouseleave(第二)函数中使用它hover():

var originalColors = [];

// Changes color on hover
    $(function() {
        $('.showlink').hover(function(){
            originalColors[$(this).index('.showlink')] = $(this).css('color');
            $(this).css('color', '#aaa');
        },
        function(){
           $(this).css('color', originalColors[$(this).index('.showlink')]);
        });
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

你也可以使用addClass()removeClass():

// Changes color on hover
$(function() {
    $('.showlink').hover(function(){
        $(this).addClass('hovered');
    },
    function(){
        $(this).removeClass('hovered');
    });
});
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

这将简单地使用CSS来应用更改的颜色,并且不需要任何类型的CSS颜色的本地存储来重新实现它mouseleave.