页面点击特效
之前在浏览一个博客时,发现了鼠标点击页面会出现文字特效,事后想着怎么实现,这里给出demo的源码和实现过程中一些需要注意的知识点。
实现的效果:鼠标点击页面时,光标处会淡入淡出一个词语
先给出demo的代码
<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>demo</title>
<style>
/* css3动画 */
@keyframes myFirst {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes mySecond {
from {
opacity: 1;
/* background-color: red */
}
to {
opacity: 0;
/* background-color: blue; */
}
}
.body {
width: 1024px;
height: 1024px;
background-color: aliceblue;
}
.newDiv {
position: absolute;
width: 40px;
height: 30px;
text-align: center;
animation: myFirst 0.8s; /* 淡入 */
animation: mySecond 0.8s; /* 淡出 */
}
[tip type="warning"]
以上代码放到前
[/tip]
var arr = ["富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治"];
let mark = true;
document.body.onmousedown = function(e) {
if (mark) {
mark = false;
var clientX = e.clientX;
var clientY = e.clientY;
var index = Math.floor(Math.random() * 8);
var text = arr[index];
createDiv(clientX, clientY, text);
var body = document.body;
var div = document.getElementsByClassName("newDiv")[0];
setTimeout(() => {
body.removeChild(div);
}, 1600);
setTimeout(()=>{
mark = true
},1600);
} else {
// alert('你点的太快了');
}
};
function createDiv(x, y, text) {
var colorArr = ["red", "yellow", "green", "blue", "orange", "black"];
var index = Math.floor(Math.random() * colorArr.length);
var color = colorArr[index];
var newDiv = document.createElement("div");
newDiv.innerText = text;
newDiv.classList.add("newDiv");
newDiv.style.color = color;
newDiv.style.opacity = 0;
newDiv.style.left = x + "px";
newDiv.style.top = y + "px";
document.body.appendChild(newDiv);
}
[tip type="warning"]
以上代码放在