一、JS改变元素样式
上一篇文章中我们尝试了使用CSS的方式通过编写@keyframes关键字进行设置动画的关键帧实现动画的制作。此次文章中将会使用完全的JS代码进行另一种方式的动画制作。
在scri标签下我们不能直接用 元素id.background-coler:red;的形式直接改变属性值,而是应该通过直接"插入"的方式进行改变。
let z=document.getElementById('z')
z.style.top=x+'px'
二、动画的制作
进行设计动画之前我们应该先了解一下定时器的概念,定时器setInterval()中包含两个参数,函数function,循环延迟。意为每经过一个循环延迟执行一次函数内的代码。
var timeid = setInterval(function(){i++}, 1000)
可以简化为以下形式
dsq=setInterval(()=>{i++},1000);
需要注意的是,循环延迟的参数单位为毫秒。
三、Math函数
在制作较为复杂的动画时我们难免会使用一些数学公式作为位置刷新的轨迹。例如让点根据sin函数进行改变:y++, x=Math.sin(y)。
以下是使用Math函数进行设计的动画
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.f{
width: 1300px;
height: 1300px;
position: relative;
border-radius: 50%;
}
.f2{
width: 1000px;
height: 1000px;
position: relative;
}
.z1{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
border-radius: 50%;
}
.z2{
width: 200px;
height: 200px;
background-color: blueviolet;
position: absolute;
border-radius: 50%;
}
.z3{
width: 800px;
height: 800px;
border: 1px solid rebeccapurple;
position: absolute;
border-radius: 50%;
top: 200px;
left: 200px;
}
.z4{
width: 400px;
height: 400px;
border: 1px solid red;
position: absolute;
border-radius: 50%;
top: 400px;
left: 400px;
}
.z5{
width: 1200px;
height: 1200px;
border: 1px solid yellowgreen;
position: absolute;
border-radius: 50%;
top: 0px;
left: 0px;
}
.z6{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
}
</style>
<body>
<div class="f">
<button onclick="start1()">开始</button>
<button onclick="stop1()">暂停</button>
<div class="z1" id="z" ></div>
<div class="z2" id="z1" ></div>
<div class="z3"></div>
<div class="z4"></div>
<div class="z5"></div>
</div>
<button onclick="strat2()">开始</button>
<div class="f2">
<div class="z6" id="z6" style="top: 0;"></div>
</div>
</body>
<script>
let dsq
function start1(){
let z=document.getElementById('z')
let z1=document.getElementById('z1')
let y=0,x,time=0,hudu,m,n
// 定时器
dsq=setInterval(()=>{
time+=1,
hudu=(2*Math.PI/360)*time
x=500+Math.sin(hudu)*300
m=500+Math.sin(hudu)*500
y=500+Math.cos(hudu)*300
n=500+Math.cos(hudu)*500
z.style.top=x+'px'
z.style.left=y+'px'
z1.style.top=m+'px'
z1.style.left=n+'px'
},0.5);}
function start2(){
let z6=document.getElementById('z6')
let a=0,b=0
let dsq1=setInterval(()=>{
a++,
b=a
z6.style.top=a+'px'
z6.style.left=b+'px'
},0.5);}
</script>
</html>