jQuery动画背景颜色slideDown

时间:2013-05-04 10:49:57

标签: javascript jquery css css3

我正在尝试在悬停元素时为背景颜色设置动画。

例如,假设我有一个div,当我悬停时,我希望背景在鼠标离开时变为红色,幻灯片和fadeOut。

$('div.Item').hover(function () {
  $(this).css('background-color', 'red').slideDown(400);
},
function () {
    $(this).css('background-color', 'transparent').fadeOut(400);
});

这有两个问题.. SlideDown不起作用,红色刚进来..也在鼠标离开时,元素完全消失(我假设因为fadeOut正在处理元素本身而不是转换为背景色。)

是否有任何教程或任何人可以帮助实现这一目标?

2 个答案:

答案 0 :(得分:3)

你可以通过将它作为背景图像来实现相同的效果,也可以使用.animate将css和动画效果一起更改而不是保持链接,这段代码会有所帮助:

$('#nav a')
.css( {backgroundPosition: "0 0"} )
.mouseover(function(){
    $(this).stop().animate(
        {backgroundPosition:"(0 250px)"}, 
        {duration:500})
    })
.mouseout(function(){
    $(this).stop().animate(
        {backgroundPosition:"(0 0)"}, 
        {duration:500})
    })

检查此LINK并查看演示!

答案 1 :(得分:0)

那是因为fadeOut是一个jQuery Object方法。它只适用于使用jQuery选择的DOM元素。 对您的问题最优雅的解决方案是使用CSS transitions

这是一个伪css snipet,其中包含您的要求:

div.Item
{
    background-color: #your-background-color;
    -webkit-transition: all 0.3s ease-out;  /* Chrome 1-25, Safari 3.2+ */
    -moz-transition: all 0.3s ease-out;  /* Firefox 4-15 */
    -o-transition: all 0.3s ease-out;  /* Opera 10.50–12.00 */
    transition: all 0.3s ease-out;  /* Chrome 26, Firefox 16+, IE 10+, Opera 12.10+ */
}
div.Item:hover
{
    background-color: #your-new-background-color; 
}

始终尝试尽可能少编写代码。并避免使用css类名中的大写字母。