思路
1、肯定是要用到css3动画
2、定时器任务(不然怎么循环播报)
开整
1、首先是css3动画,通过最直观的效果,这里运用到了opacity和位移
index.vue
<!-- 弹幕 -->
<div id="card-toast"> </div>
<style lang='less'>
// 设置弹幕div的初始位置
.card-toast {
position: absolute;
left: 2rem;
background: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 1.2rem;
padding: 0.5rem;
opacity: 0;
border-radius: 1.5rem;
}
// css动画
@keyframes fadeIn {
0% {
opacity: 0;
top: 12rem;
}
60% {
opacity: 0.5;
top: 11rem;
}
100% {
opacity: 1;
top: 10rem;
}
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0;
top: 12rem;
}
60% {
opacity: 0.5;
top: 11rem;
}
100% {
opacity: 1;
top: 10rem;
}
}
@-moz-keyframes fadeIn {
0% {
opacity: 0;
top: 12rem;
}
60% {
opacity: 0.5;
top: 11rem;
}
100% {
opacity: 1;
top: 10rem;
}
}
@-o-keyframes fadeIn {
0% {
opacity: 0;
top: 12rem;
}
60% {
opacity: 0.5;
top: 11rem;
}
100% {
opacity: 1;
top: 10rem;
}
}
@-ms-keyframes fadeIn {
0% {
opacity: 0;
top: 12rem;
}
60% {
opacity: 0.5;
top: 11rem;
}
100% {
opacity: 1;
top: 10rem;
}
}
@keyframes fadeOut {
0% {
opacity: 0.5;
top: 10rem;
}
60% {
opacity: 0.2;
top: 9rem;
}
100% {
opacity: 0;
top: 8rem;
}
}
@-webkit-keyframes fadeOut {
0% {
opacity: 0.5;
top: 10rem;
}
60% {
opacity: 0.2;
top: 9rem;
}
100% {
opacity: 0;
top: 8rem;
}
}
@-moz-keyframes fadeOut {
0% {
opacity: 0.5;
top: 10rem;
}
60% {
opacity: 0.2;
top: 9rem;
}
100% {
opacity: 0;
top: 8rem;
}
}
@-o-keyframes fadeOut {
0% {
opacity: 0.5;
top: 10rem;
}
60% {
opacity: 0.2;
top: 9rem;
}
100% {
opacity: 0;
top: 8rem;
}
}
@-ms-keyframes fadeOut {
0% {
opacity: 0.5;
top: 10rem;
}
60% {
opacity: 0.2;
top: 9rem;
}
100% {
opacity: 0;
top: 8rem;
}
}
.fadeOut {
animation: fadeOut 2s;
}
.fadeIn {
animation: fadeIn 2s;
}
</style>
为了效果看起来更舒适,这里采用的三段,当然你也可以多写几段,根据自己的实际情况来
基本效果出来,现在来写逻辑
先自定义一个数组,用来存放弹幕播报的数据
然后通过定时任务,去触发这个效果
<script>
export default {
data() {
return {
toastArr: [
"1师傅邀请了1个人,获得10元奖励",
"2师傅邀请了1个人,获得10元奖励",
"3师傅邀请了1个人,获得10元奖励"
],
timer: []
}
},
created() {
// 调用定时任务,设置时间
this.toastArr.forEach((item, index) => {
this.toast((index + 1) * 2000, item);
});
},
destroyed() {
// 别忘了清除定时器
this.clearToast();
},
methods: {
toast(time, message) {
this.timer.push(
setInterval(() => {
const parent = document.getElementById("card-toast");
// 判断当前dom里面有没有插入弹幕,有的话就清除,不然会造成重叠
if (parent.childNodes.length != 0) {
parent.innerHTML = "";
}
const el = document.createElement("div");
parent.appendChild(el); // 插入弹幕
el.innerHTML = "";
el.innerHTML = message;
// 插入css
el.setAttribute("class", "card-toast");
el.classList.add("fadeIn");
el.classList.remove("fadeIn");
el.classList.add("fadeOut");
// 这里监听动画结束,动画结束移除dom,不然会一直插入dom,影响性能
el.addEventListener("animationend", () => {
parent.innerHTML = "";
parent.removeChild(el);
});
el.addEventListener("webkitAnimationEnd", () => {
parent.innerHTML = "";
parent.removeChild(el);
});
}, time)
);
},
clearToast() {
this.timer.forEach(item => {
clearInterval(item);
});
},
}
}
</script>
好了,一个简单的弹幕播报就完成了,快去试试吧