【问题标题】:Animating mouse leave with CSS and jQuery?用 CSS 和 jQuery 动画鼠标离开?
【发布时间】:2013-06-14 14:54:17
【问题描述】:
我正在使用 CSS 过渡在鼠标悬停时为背景颜色设置动画。
我有以下代码:
div {
width: 100px;
height: 100px;
background: red;
}
div:hover {
background: green;
transition: all 0.5s ease-in-out;
}
<div></div>
此代码仅在鼠标打开时为背景颜色设置动画。它不会重新激活鼠标。我有两个问题:
如何使用 CSS 为鼠标设置动画?
如何使用 jQuery only 做到这一点?
jsfiddle:http://jsfiddle.net/fz39N/
【问题讨论】:
标签:
jquery
html
css
css-transitions
【解决方案1】:
1) 你把你的css改成
div {
width: 100px;
height: 100px;
background: red;
transition: background 0.5s ease-in-out;
}
div:hover {
background: green;
}
FIDDLE
设置过渡到元素,而不是伪类。
2)
使用 jQuery,您要么需要两个元素来交叉淡入淡出,要么需要一个彩色动画插件。 jQuery UI 内置了彩色动画,然后你就可以这样做了:
$('div').on({
mouseenter: function() {
$(this).animate({backgroundColor: 'green'},1000)
},
mouseleave: function() {
$(this).animate({backgroundColor: 'red'},1000)
}
});
FIDDLE
如果您还没有将 jQuery UI 用于其他用途,我建议您使用更小的插件之一,例如 this one !!
【解决方案2】:
这应该可以解决您的问题
div {
width: 100px;
height: 100px;
background-color: red;
transition: background-color 0.5s;
}
div:hover {
background-color: green;
}