效果:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS生成动画</title>
<style type="text/css">
*{
margin: auto;
padding: 0px;
background-color: orange;
}
@keyframes myMove{
from{transform: rotateY(0deg);}/*设置在Y轴上的旋转*/
to{transform: rotateY(360deg);}
}
</style>
</head>
<body οnlοad="init()">
<script>
var i = 0,j = 0;
function init(){
var totalA = 36,deg = 360/totalA;/*指定每个box中a标签的个数*/
for(i = 0;i < 2;i ++){/*生成两个box*/
var box = document.createElement("div");
box.setAttribute("id","box");
box.style.height = "0px";/*隐藏box*/
box.style.marginLeft = "50%";
box.style.marginTop = "2px";
box.style.position = "absolute";
box.style.transformStyle = "preserve-3d";/*设置3D转化模式*/
box.style.animation = "myMove 3s infinite linear alternate";/*为自己的动画设置名字、周期、次数、速度(linear是线性的,速度相同)、来回转(后缀reverse表示反向来回转*/
if(i == 1){
box.style.animation = "myMove 3s infinite linear alternate-reverse";/*第二个box设置反向转*/
}
for(j = 0;j < totalA;j ++){
var newA = document.createElement("a");
newA.style.display = "block";
newA.style.padding = "9px";
newA.style.borderRadius = "50%";
newA.style.backgroundColor = "white";
newA.style.transform = "rotateY(" + j*deg +"deg)translateZ(270px)";/*设置a标签在Y轴上旋转的度数,依次递增;并设置a标签和Z轴(由屏幕从里向外)的距离*/
if(i == 1){
newA.style.backgroundColor = "black";
newA.style.transform = "rotateY(-" + j*deg +"deg)translateZ(270px)";
}
box.appendChild(newA);/*在box中放入a标签*/
}
document.body.appendChild(box);/*在body中放入box*/
}
}
function clear(){
for(i = 0;i < 8;i ++){
var box = document.getElementById("box");/*通过ID获取box*/
box.remove(box.childNodes[0]);/*依次将box移除*/
}
}
setInterval(init,3000);
setInterval(clear,9000);
</script>
</body>
</html>