Javascript jQuery 缓慢更改 css 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6950988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:54:35  来源:igfitidea点击:

jQuery change css attribute slowly

javascriptjqueryhtmlcssfade

提问by Grigor

I have this code

我有这个代码

$('#uiAdminPanelMenu li a').hover( function(){
    $(this).css('background-color', '#D3E1FA';
 },
 function(){
    $(this).css('background-color', '#F4F4F4');
});

it changes the background color of the link, but I want it to change it slowly, kinda like fade effect, but for this case.

它改变了链接的背景颜色,但我希望它慢慢改变,有点像淡入淡出效果,但对于这种情况。

回答by awesomesyntax

You can accomplish the same thing with CSS3 transitions. The result will almost be the exact same.

您可以使用 CSS3 过渡完成同样的事情。结果几乎完全相同。

#uiAdminPanelMenu li a {
    background-color: F4F4F4;
    -webkit-transition: background-color 0.4s ease;
    -moz-transition: background-color 0.4s ease;
    -o-transition: background-color 0.4s ease;
    transition: background-color 0.4s ease;
}

#uiAdminPanelMenu li a:hover {
    background-color: D3E1FA;
}

回答by Paul

You want to use animate(), but you also need the Color Plugin for jQuery.

您想使用animate(),但还需要用于 jQuery颜色插件

With the color plugin included, the following code works well:

包含颜色插件后,以下代码运行良好:

$('#uiAdminPanelMenu li a').hover( function(){
    $(this).animate({'background-color': '#D3E1FA'}, 'slow');
 },
 function(){
    $(this).animate({'background-color': '#F4F4F4'}, 'slow');
});

回答by Sujoy

May be its very late for answering this question, but still wanted to provide an alternate solution that worked for me. (Both the answers provided earlier will work). I used CSS Animation and that worked better for me than jquery animate in few other cases as well. You can try the below -

回答这个问题可能已经很晚了,但仍然想提供一个对我有用的替代解决方案。(前面提供的两个答案都有效)。我使用了 CSS Animation,在其他一些情况下,它比 jquery animate 更适合我。你可以试试下面的——

// 'bcolor' is animation keyframe name defined later

// 'bcolor' 是后面定义的动画关键帧名称

#uiAdminPanelMenu li a:hover {
    -webkit-animation-name: bcolor; 
    -webkit-animation-duration: 1s;   
    -webkit-animation-fill-mode: forwards;
    -moz-animation-name: bcolor;  
    -moz-animation-duration: 1s;   
    -moz-animation-fill-mode: forwards; 
    animation-name: bcolor;
    animation-duration: 1s;    
    animation-fill-mode: forwards;
}

@-webkit-keyframes shadeOn {
    from {background-color: #F4F4F4;}
    to {background-color: #D3E1FA;}
}
@-moz-keyframes shadeOn {
    from {background-color: #F4F4F4;}
    to {background-color: #D3E1FA;}
}
@keyframes shadeOn {
    from {background-color: #F4F4F4;}
    to {background-color: #D3E1FA;}
}