仅使用CSS更改颜色几秒钟 [英] Change color for some seconds using only CSS

查看:68
本文介绍了仅使用CSS更改颜色几秒钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在X悬停时将div的颜色更改X秒钟,然后仅使用CSS返回其原始颜色?

Is it possible to change the color of a div on hover for X seconds, then return to its original color using only CSS?

我不希望颜色之间出现任何淡入或淡出.例如,如果我想在悬停时将div的颜色更改为黄色1秒钟,则必须将其保持黄色1秒钟,然后立即返回原始颜色.

I do not want any fade ins or outs between the color. For example, if I want to change the color of the div to yellow for 1 second on hover, it must remain yellow for 1 second, then immediately return to the original color.

我所拥有的( http://jsfiddle.net/hZ49y/1/)迄今为止.它可以像我上面描述的那样工作,但是我觉得这种使用 animation 的方式不直观且难以理解.我是否应该坚持为此目的使用JavaScript?有哪些替代方案?

This (http://jsfiddle.net/hZ49y/1/) is what I have so far. It works as I described above, but I feel that this way of using animation is not intuitive and hard to understand. Should I stick to using JavaScript for this purpose? What are some alternatives?

推荐答案

可能,但需要一些数学知识!

It is possible, but requires some math!

这是 小提琴

Here is the Fiddle

您必须使用动画的另一个参数: animation-iteration-count 作为 1

You must use another parameter of animation: animation-iteration-count as 1

div:hover {
    animation: myfirst 2s 1;
}

@keyframes myfirst
{
    0%      {background:red;}
    25%     {background:yellow;}
    75%     {background:yellow;}
    100%    {background:red;}
}

这将使用以下关键帧" 来执行 4s 动画:

0s>红色
1s>黄色(此处停留2秒)
3s>黄色
4s>红色

0s > red
1s > yellow (stays 2 seconds here)
3s > yellow
4s > red

唯一的问题是动画会在鼠标移出时停止.但是您可以使用 javascript 激活动画(通过切换类),因此动画不会在鼠标移出时停止.

The only problem is that the animation stops on mouse out. But you can use javascript to activate the animation (by toggle a class), so the animation doesn't stops on mouse out.

更新:

这是 小提琴 ,其中包含 js 来控制 css 动画.

这篇关于仅使用CSS更改颜色几秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆