css3 animation动画使用

时间:2022-04-30 01:37:24
 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style media="screen">
.basic{
background-color: red;
/* width: 300px;
height: 300px; */
} @keyframes animate1
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
} @-moz-keyframes animate1 /* Firefox */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
} @-webkit-keyframes animate1 /* Safari 和 Chrome */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
} @-o-keyframes animate1 /* Opera */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
} .animate2 { animation: animate1 5s;
-moz-animation: animate1 5s; /* Firefox */
-webkit-animation: animate1 5s; /* Safari 和 Chrome */
-o-animation: animate1 5s; /* Opera */ } </style>
</head>
<body>
<div class="basic" id="div1">
hello world.
</div> <button type="button" name="button">点击应用动画</button> <script type="text/javascript">
const btn = document.getElementsByName('button')[0];
const div = document.getElementById("div1");
btn.addEventListener('click', ()=>{
console.log("点击按钮。。。");
if(div.classList.contains("basic")){
div.classList.remove("basic");
}
div.classList.add("animate2");
});
</script>
</body>
</html>

1. 使用@keyframes定义一个动画效果。

 @keyframes animate1
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
} @-moz-keyframes animate1 /* Firefox */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
} @-webkit-keyframes animate1 /* Safari 和 Chrome */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
} @-o-keyframes animate1 /* Opera */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
}

2.将动画效果先绑定到css类上。

 .animate2 {

   animation: animate1 5s;
-moz-animation: animate1 5s; /* Firefox */
-webkit-animation: animate1 5s; /* Safari 和 Chrome */
-o-animation: animate1 5s; /* Opera */ }

3.将动画效果应用到指定的元素上。

const btn = document.getElementsByName('button')[0];
const div = document.getElementById("div1");
btn.addEventListener('click', ()=>{
console.log("点击按钮。。。");
if(div.classList.contains("basic")){
div.classList.remove("basic");
}
div.classList.add("animate2");
});

当点击按钮时,就会将定义的动画效果应用到div上。