FCC---Use CSS Animation to Change the Hover State of a Button---鼠标移过,背景色变色,用0.5s的动画制作

You can use CSS @keyframes to change the color of a button in its hover state.

Here's an example of changing the width of an image on hover:

如下是鼠标移过图片,宽度变化的小动画

 1 <style>
 2   img:hover {
 3     animation-name: width;
 4     animation-duration: 500ms;
 5   }
 6 
 7   @keyframes width {
 8     100% {
 9       width: 40px;
10     }
11   }
12 </style>
13 
14 <img src="https://bit.ly/smallgooglelogo" alt="Google's Logo" />

 

练习题目:

Note that ms stands for milliseconds, where 1000ms is equal to 1s.

Use CSS @keyframes to change the background-color of the button element so it becomes #4791d0 when a user hovers over it.

The @keyframes rule should only have an entry for 100%.

 

练习代码:

 1 <style>
 2   button {
 3     border-radius: 5px;
 4     color: white;
 5     background-color: #0F5897;
 6     padding: 5px 10px 8px 10px;
 7   }
 8 
 9   button:hover {
10     animation-name: background-color;
11     animation-duration: 500ms;
12   }
13   @keyframes background-color {
14     100% {
15       background-color: #4791d0;
16     }
17   }
18 </style>
19 <button>Register</button>

 

效果如下:

 

 

问题: 

因为持续时间只设置了0.5s,所以动画结束,按钮的颜色就变暗了。

如果希望鼠标放在上面,按钮一直保持高亮

通过如下设置,可以改进:

 

That's great, but it doesn't work right yet.

Notice how the animation resets after 500ms has passed, causing the button to revert back to the original color.

You want the button to stay highlighted.

This can be done by setting the animation-fill-mode property to forwards. The animation-fill-mode specifies the style applied to an element when the animation has finished. You can set it like so:

animation-fill-mode: forwards;

 

所以添加后代码:

 1 <style>
 2   button {
 3     border-radius: 5px;
 4     color: white;
 5     background-color: #0F5897;
 6     padding: 5px 10px 8px 10px;
 7   }
 8   button:hover {
 9     animation-name: background-color;
10     animation-duration: 500ms;
11     /* add your code below this line */
12     animation-fill-mode: forwards;
13     /* add your code above this line */
14   }
15   @keyframes background-color {
16     100% {
17       background-color: #4791d0;
18     }
19   }
20 </style>
21 <button>Register</button>

 

posted @ 2019-10-25 15:34  jane_panyiyun  阅读(196)  评论(0编辑  收藏  举报