主要使用 CSS 實現的動畫效果,其中 CSS 需要使用 Less 編譯完成。效果如下圖:
Html 代碼:
<!DOCTYPE html>
<html>
<head>
<title>Hypnotic Ring</title>
<meta charset="utf-8">
<link rel="stylesheet" href="./Hyp.css">
</head>
<body>
<div class="frame"></div>
<script src="./Hyp.js"></script>
</body>
</html>
Less 代碼:
.frame{
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: 400px;
margin-top: -200px;
margin-left: -200px;
border-radius: 2px;
box-shadow: 1px 2px 10px 0px rgba(0, 0, 0, 0.3);
overflow: hidden;
/*background-color: #27ae60;*/
background-color: skyblue;
color: #fff;
}
.circle{
position: absolute;
width: 200px;
height: 200px;
top: 100px;
left: 100px;
border-radius: 50%;
border: 2px dotted #fff;
transform-origin: 50% 50%;
/*transform: scale(2) translate(0, 0);*/
}
/* less 用遞歸實現循環 */
.circleFunction(@index) when (@index <= 50) {
.circle-@{index}{
animation: circle 10s ease-in-out @index/5s infinite backwards;
// z-index: @index;
}
// 遞歸調用
.circleFunction(@index+1);
}
// 從參數 1 開始調用
.circleFunction(1);
/* 動畫 */
@keyframes circle{
0%{
transform: scale(0) translate(-100px, -200px);
opacity: 0.4;
}
100%{
transform: scale(3.5) translate(0, 0);
opacity: 1;
}
}
在使用 less 前需要完成兩個步驟:
1、全局安裝 less:npm install -g less(注:沒有 npm 工具包的需要先去官網下載自帶 npm 的 node 。網址:https://nodejs.org/en/)
2、編譯 less: lessc 要編譯的文件名.less 編譯後的文件名.css
如:lessc Hyp.less Hyp.css,編譯成 css 文件後,導入就行了。
Js 代碼:
var frame = document.querySelector('.frame');
for(var i = 0; i < 50; i++){
var div = document.createElement('div');
div.className = 'circle';
div.classList.add('circle-' + (i + 1));
frame.appendChild(div);
}
該動畫效果來自一個專門練習 CSS 的網址:https://100dayscss.com/?dayIndex=62
關於 Less的介紹,和更多 css 動畫可以去博主的 github :https://github.com/cao-lianhui/CSS100day