<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
background-color: skyblue
}
.star {
display: flex;
justify-content: center;
align-items: center;
/* 背景颜色渐变 */
background-image: linear-gradient(to right, rgb(233, 233, 235), transparent);
width: 320px;
border-radius: 32px;
position: fixed;
animation-duration: 10s;
}
.star p {
margin: 0;
width: 240px;
/* 文字超出以省略号显示 */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.star p:first-child {
font-size: 12px;
color: rgb(235, 236, 237);
}
.star p:last-child {
color: white;
}
img {
margin-right: 10px;
}
</style>
<body>
<!-- <div class="star">
<img src="img/星星.png" alt="">
<div class="word">
<p>#青春是一个说走就走的旅程</p>
<p>哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈hahahha</p>
</div>
</div> -->
</body>
<script>
let screenWidth = window.innerWidth + 400
let screenHeight = window.innerHeight
let arr = [{ text: '我是哈哈哈哈哈哈哈哈哈哈哈哈', name: 'one' }, { text: '我是哈哈哈哈哈哈哈哈哈哈哈哈', name: 'two' }, { text: '我是哈哈哈哈哈哈哈哈哈哈哈哈', name: 'three' }, { text: '我是哈哈哈哈哈哈哈哈哈哈哈哈', name: 'four' }]
// var timer = setInterval(function () {
arr.forEach((ele, index) => {
starStart(ele.text, ele.name, index)
})
function starStart(content, name, index) {
let style = document.styleSheets[0];
let body = document.querySelector('body')
let div = document.createElement('div')
let Top = Math.floor(Math.random() * (screenHeight - 63)) + 'px'
let outTime = index * 1000
div.className = 'star'
div.style.animationName = name
// 将消息间隔1秒展出
setTimeout(function () {
// 写入动画样式
style.insertRule(`@keyframes ${name} {
0% {
top: ${Top};
right: 0;
}
100% {
top: ${Top};
right: ${screenWidth}px;
}
}`);
div.innerHTML = `
<img src="img/星星.png" alt="">
<div class="word">
<p>#青春是一个说走就走的旅程</p>
<p>${content}</p>
</div>
`
body.appendChild(div)
// 动画完成后销毁
setTimeout(function () {
div.style.display = 'none'
}, 10000)
}, outTime)
}
</script>
</html>
所用到的知识有:
css动画:animation-name、animation-duration、@keyframes name{0%{style} 100%{style}}想要实现动画,三者缺一不可。
文字超出以省略号显示:overflow:hiddle;text-overflow:ellipsis;white-space:nowrap;
使用js在css中写入动画:let style = document.styleSheets[0] //拿到页面的样式表 style.insertRule(@keyframes样式) //进行动画编写
背景颜色渐变:background-image:linear-gradient(to right, rgb(233, 233, 235), transparent)
大体思路:
首先编辑好消息的基本样式,再使用js 创建一个添加元素的函数。在函数中进行相关div的添加和样式的写入,在获取页面视图的高度利用Math函数在随机的高的对相关div进行添加,之后再利用setTimeOut()对div的添加进行一个定时,最后循环该函数即可。