1.barrage.less
html,body{
width:100%;
}
.cute-barrage{
width: 100%;
height: 100px; /*確定彈幕長度*/
position: absolute;
top: 1.5rem; /*確定彈幕高度*/
left: 0;
overflow-y: hidden; /*橫向超出部分隱藏*/
.barrage-div{
position: absolute;
left: 0;
bottom: 0; /*保證一開始在界面外側,從右向左就是right,從左向右就是left*/
height: 0.6rem;
background-color: rgba(255, 255, 255, 0.9);
border-radius: 2rem;
white-space: nowrap; /*確保內容在一行顯示,不然移動到最後會折行*/
img{
width: 0.5rem;
height: 0.5rem;
vertical-align: middle; //內聯塊元素,居中對齊
padding-left: 0.05rem;
border-radius: 50%;
}
span{
font-size: 14px;
padding: 0 0.1rem;
line-height: 0.6rem; //內聯塊元素,居中對齊四個缺一不可
height: 0.6rem; //內聯塊元素,居中對齊四個缺一不可
display: inline-block; //內聯塊元素,居中對齊四個缺一不可
vertical-align: middle; //內聯塊元素,居中對齊四個缺一不可
i{
color: #fe5453;
font-weight: 700;
}
}
}
}
2.barrage.vue
<style lang="less" src="./barrage.less"></style>
<template>
<div class="barrage">
<div class="cute-barrage">
<div class="barrage-div">
<img
src="http://kw1-1253445850.file.myqcloud.com/static/image/stimg_7656dc02eb1cd13adbacbdd2695dc3a8.jpg"
/>
<span>
麼麼嗒今天提現
<i>1Q幣</i>
</span>
</div>
<div class="barrage-div">
<img
src="http://kw1-1253445850.file.myqcloud.com/static/image/stimg_632fecdcb52417cb8ab89fa283e07281.jpg"
/>
<span>
橘色的大耳朵貓今天提現
<i>5Q幣</i>
</span>
</div>
<div class="barrage-div">
<img
src="http://kw1-1253445850.file.myqcloud.com/static/image/stimg_632fecdcb52417cb8ab89fa283e07281.jpg"
/>
<span>
丶鹿鍋裏面裝着吳奶包今天提現
<i>3Q幣</i>
</span>
</div>
</div>
</div>
</template>
<script>
export default {
name: "barrage",
components: {},
props: {},
data() {
return {};
},
watch: {},
computed: {},
methods: {},
created() {},
mounted() {
for (
let i = 0;
i < document.getElementsByClassName("barrage-div").length;
i++
) {
var height = document.getElementsByClassName("barrage-div")[i].clientHeight;
document.getElementsByClassName("barrage-div")[i].style.bottom = -height;
// document.getElementsByClassName("barrage-div")[i].style.top = topRandom; //將彈幕移動到屏幕外面,正好超出的位置
//拼寫動畫幀函數,記得每個ani要進行區分,寬度從自己的負寬度移動一整個屏幕的距離
var keyframes = `\
@keyframes ani${i}{
form{
bottom:${-height}px;
}
to{
bottom:100px;
}
}\
@-webkit-keyframes ani${i}{
form{
bottom:${-height}px;
}
to{
bottom:100px;
}
}`;
// 創建style標籤
const style = document.createElement("style");
// 設置style屬性
style.type = "text/css";
// 將 keyframes樣式寫入style內
style.innerHTML = keyframes;
// 將style樣式存放到head標籤
document.getElementsByTagName("head")[0].appendChild(style);
//定義動畫速度列表
var aniList = [4, 4, 4, 4, 4];
//取數組的隨機數,0,1,2,3,4
var aniTime = Math.floor(Math.random() * 5);
//給當全前彈幕添加animation的css
//延遲的時間用每個的*1.5倍,這個可變
document.getElementsByClassName("barrage-div")[i].style.animation=`ani${i} ${aniList[aniTime]}s linear ${i * 1.5}s`
document.getElementsByClassName("barrage-div")[i].style.webkitAnimation=`ani${i} ${aniList[aniTime]}s linear ${i * 1.5}s`
}
}
};
</script>