用CSS和jQuery动画鼠标离开



我正在使用CSS过渡来动画鼠标悬停时的背景颜色。

我有以下代码:

div {
  width: 100px;
  height: 100px;
  background: red;
}
div:hover {
  background: green;
  transition: all 0.5s ease-in-out;
}
<div></div>

此代码仅在鼠标上激活背景颜色。它不会让鼠标复活。我有两个问题:

  1. 如何使用CSS动画鼠标关闭?

  2. 我如何做到这一点使用jQuery仅?

jsfiddle: http://jsfiddle.net/fz39N/

1)修改css为

div {
    width: 100px;
    height: 100px;  
    background: red;
    transition: background 0.5s ease-in-out;
}
div:hover {
    background: green;
}

小提琴

设置元素的过渡,而不是伪类。


2)使用jQuery,你要么需要两个元素来交叉渐变,要么需要一个颜色动画插件。jQuery UI内置了颜色动画,然后你可以这样做:

$('div').on({
    mouseenter: function() {
        $(this).animate({backgroundColor: 'green'},1000)
    },
    mouseleave: function() {
        $(this).animate({backgroundColor: 'red'},1000)
    }
});

小提琴

如果你还没有在其他地方使用jQuery UI,我建议你使用一个小得多的插件,就像这个!!

这应该能解决你的问题

div {
    width: 100px;
    height: 100px;  
    background-color: red;
    transition: background-color 0.5s;
}
div:hover {
    background-color: green;
}

最新更新