使用 CSS 和 jQuery 动画鼠标离开?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17168088/
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-26 18:34:18  来源:igfitidea点击:

Animating mouse leave with CSS and jQuery?

jqueryhtmlcsscss-transitions

提问by It worked yesterday.

I am using CSS transitions to animate a background colour on mouse hover.

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

I have the following code:

我有以下代码:

div {
  width: 100px;
  height: 100px;
  background: red;
}

div:hover {
  background: green;
  transition: all 0.5s ease-in-out;
}
<div></div>

This code only animates the background colour on mouse on. It doesn't reanimate the mouse off. I have 2 questions:

此代码仅动画鼠标上的背景颜色。它不会重新激活鼠标。我有两个问题:

  1. How do I animate the mouse off using CSS?

  2. How do I do this using jQuery only?

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

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

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

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

回答by adeneo

1) You change your css to

1)你改变你的CSS

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

div:hover {
    background: green;

}

FIDDLE

小提琴

setting the transition to the element, and not the pseudo class.

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



2)

2)

With jQuery you'll either need two elements to cross fade, or a color animation plugin. jQuery UI has color animation built in, and then you can do :

使用 jQuery,你要么需要两个元素来交叉淡入淡出,要么需要一个彩色动画插件。jQuery UI 内置了彩色动画,然后您可以执行以下操作:

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

FIDDLE

小提琴

If you're not already using jQuery UI for something else, I'd suggest using one of the much smaller plugins, like this one!!

如果您还没有将 jQuery UI 用于其他用途,我建议您使用较小的插件之一,例如这个插件!

回答by mohkhan

This should solve your problem

这应该可以解决您的问题

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

div:hover {
    background-color: green;
}