先上图:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container"></div>
<script src="app.js"></script>
</body>
</html>
CSS:
body{
background-color: black;
}
@keyframes rotate {
from{
transform: rotateX(0deg) rotateY(0deg);
}
to{
transform: rotateX(360deg) rotateY(360deg);
}
}
JS:
/**
* Created by Administrator on 2017/8/15.
*/
(function () {
//同步创建两套子元素,根据传入的className名设置立方大小和样式
function cube(className,maxWidth) {
var width = className==="out-cube"?maxWidth:maxWidth/2;
var bg = document.createElement("div");
bg.style.cssText = "width: "+width+"px;height: "+width+"px;position: absolute;";
var ul = document.createElement("ul");
bg.appendChild(ul);
ul.style.cssText = "width: "+width+"px;height: "+width+"px;list-style: none;position: relative;transform-style: preserve-3d;";
ul.setAttribute("class",className);
var styles = ["background-color: #0970ff;transform: translateZ("+width/2+"px);","background-color: #bb5eff;transform: translateZ("+-width/2+"px);","background-color: #b9ffae;transform: rotateY(-90deg) translateZ("+width/2+"px);","background-color: #ffdf38;transform: rotateY(90deg) translateZ("+width/2+"px);","background-color: #61ff4d;transform: rotateX(-90deg) translateZ("+width/2+"px);","background-color: #ff328a;transform: rotateX(90deg) translateZ("+width/2+"px);"];
for (var i=0;i<styles.length;i++){
var li = document.createElement("li");
var css = styles[i]+"opacity: 0.4;width: "+width+"px;height: "+width+"px;position: absolute;";
css+=className==="in-cube"?"left: 50%;top: 50%;":"";
li.style.cssText = css;
ul.appendChild(li);
}
return bg;
}
//封装创建立方体元素的函数
function doubleCub(width) {
var container = document.createElement("div");
//设置父元素样式调用rotate方法
container.style.cssText = "width: "+width+"px;height: "+width+"px;margin: 200px auto;transform-style: preserve-3d;animation: rotate 5s linear 0s infinite;";
//调用cube函数同步创建两套子元素
//大立方
container.appendChild(cube("out-cube",width));
//小立方
container.appendChild(cube("in-cube",width));
return container;
}
//封装init函数将元素放到body里并传参设置立方体大小
function init() {
document.body.appendChild(doubleCub(200));
}
init();
})();