数据格式
this.discountList = [
{ content: '恭喜用户Time🙏(拒微拒礼)获得9月16日全场礼物5折奖励!' },
{ content: '111111111111111111' },
{ content: '2222222222222222' },
{ content: '5555555555555555555' }]
componentDidMount生命周期中调用this.initDanmu()方法初始化轮播效果
initDanmu = () => {
$.extend({
'danmuOption': (f1, index) => {
for (let i = 0; i < f1.children().length; i++) {
const item = f1.children()[i]
setTimeout(this.texBarrScroll.bind(this, $(item), 'timer_' + index + '_' + i), Math.floor((i + Math.random())) * 1000)
}
}
})
$('.bullet').each((index) => { $.danmuOption($('.bullet').eq(index), index) })
}
texBarrScroll = (element, timer) => {
let num = 333
function goLeft() {
// 750是根据你给的尺寸,可变的
if (num === -Math.floor(element.width() / 2)) { num = 0 }
num -= 1
element.css({ left: num })
}
// 设置滚动速度
if (this[timer]) { clearInterval(this[timer]) }
this[timer] = setInterval(goLeft, 25)
}
bulletCom = (danMuList) => {
const data = this.initDanmuData(danMuList)
return (
data.map((item, index) => {
return <ul key={index} className="discount-text">
{
item && item.length > 0 ? item.map((v, ki) => {
let value = v ? v : {}
const num = value.length || 0
let wClass = this.getBlessWidth(num)
return <li key={ki} className={'discount-text' + wClass}>{value.content}</li>
}) : ''
}
</ul>
})
)
}
initDanmuData = (danMuList) => {
const data = [[]]
for (let i = 0; i < danMuList.length; i++) {
const item = danMuList[i]
data[0].push(item)
}
for (let j = 0; j < data.length; j++) {
let item = data[j]
data[j] = item.concat(Array.from(data[j]))
}
return data
}
getBlessWidth = (length) => {
if (length >= 0 && length <= 5) {
return 'w-5'
}
if (length > 5 && length < 10) {
return 'w-10'
}
if (length >= 10 && length < 15) {
return 'w-15'
}
if (length >= 15 && length < 20) {
return 'w-15'
}
return 'w-15'
}
html书写
<div className="bullet">
{this.bulletCom(this.discountList)}
</div>
css样式(可自调)
.bullet {
position: relative;
width: 620px;
height: 44px;
margin: 0 auto;
overflow: hidden;
top:30px;
}
.discount-text {
display: flex;
position: absolute;
left: 100vw;
>li {
width: max-content;
margin-right: 100px;
white-space: nowrap;
font-size: 32px;
font-family: PingFangSC-Thin, PingFang SC;
font-weight: 100;
color: #FFFFFF;
line-height: 44px;
}
}