点击页面弹出文字动画效果
introduce
在博客园查询资料的时候,经常会有一些小的惊喜,比如点击页面,会弹出一些文字,向上浮动,然后消失,显得无聊,我就做了一个demo
tool
- 首推vscode,带上插件真的是飞一般的感觉
- chrome,浏览器自带的审查元素是我见过最棒的。
- js原生函数以及css3动画函数
thought
- 在页面绑定函数,点击页面触发函数。
- 取得当前点击的位置,采用event.page取得(取得的是文档的左边缘和上边缘)
- 把所有想在页面展示的字符串放到数组里。判断当前索引的是否为空。不为空就在页面创建一个元素,内容为字符串,设置位置为鼠标点击的位置。为空则索引归零。每次点击成功后索引+1;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./index.css">
<link rel="stylesheet" href="./animote.css">
<title>text-animation</title>
</head>
<body class="body">
<div class="center">
<p>你的眼中有万千星辰</p>
<p>左眼一千</p>
<p>右眼一万</p>
</div>
<script src="./index.js"></script>
</body>
</html>
index.css
*{
padding: 0;
margin: 0;
}
.body {
width: 100%;
height: 100%;
/* text-align: center; */
/* align-items: center;
justify-content: center;
display: flex */
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
text-align: center
}
animote.css
.text_popup{
animation :textPopUp 1s;
color: blue;
user-select: none;
white-space: nowrap;
position: absolute;
z-index: 999;
}
@keyframes textPopUp {
0%, 100% {
opacity: 0;
}
10% {
opacity: 1;
}
100% {
transform: translateY(-50px);
}
}
index.js
var showText = function(arr, option) {
if (!arr || arr.length == 0) {
return ;
}
var index = 0;
document.documentElement.addEventListener("click", function(event) {
var x = event.pageX;
console.log(x)
var y = event.pageY;
var text = document.createElement("span");
text.setAttribute("class", 'text_popup');
this.appendChild(text);
if (arr[index]) {
text.innerHTML = arr[index];
} else {
index = 0;
text.innerHTML = arr[index];
}
text.addEventListener("animationend", function() {
text.parentNode.removeChild(text);
})
text.style.left = (x - text.clientWidth / 2) + "px";
text.style.top = (y - text.clientHeight / 2) + "px";
index ++
})
}
showText(['行也欢喜','停也欢喜','眉目带笑','醉如春风','浮生如梦','岁月如舟'])
writer&contact
Jontyy jontyy@163.com