技术栈:vue2
效果如下:
1.html使用双层结构嵌套
<div class="content-wrap">
<span class="notice-wrap">图标</span>
<!-- 外层 -->
<div class="content">
<!-- 内层滚动 -->
<span :style="{'animation-duration': durarion}" class="content-item" >
<span>{{ content}}</span>
</span>
</div>
<i >关闭</i>
</div>
2.根据内容计算滚动速度
export default {
props: {
content: {
type: Object,
required: true
}
},
data() {
return {
}
},
computed: {
durarion() {
const len = this.content && this.content.length
return len / 5 + 's'
}
}
}
3.样式
<style rel="stylesheet/scss" lang="scss" scoped>
.content {
position: relative;
height: 20px;
left: 45px; // 留出左边放置图标
width: calc(100% - 80px); // 留出右边防止关闭按钮
overflow: hidden; // 设置超出隐藏
.content-item {
display: inline-block;
position: absolute;
left: 0;
top: 2px; // 居中调整
font-size: 12px;
animation: run 35s linear 0s infinite; // 设置动画
white-space: nowrap; // 设置不换行
&:hover {
animation-play-state: paused; // hover上去停止
}
}
}
@keyframes run {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
</style>
4.无缝滚动实现,使内容重复几次
<div class="content">
<span :style="{'animation-duration': durarion}" class="content-item" >
<!-- 重复内容 -->
<span v-for="n in repeatNum" :key="'tip-' + n" class="tip-content">
<span>{{ content}}</span>
</span>
</span>
</div>
export default {
props: {
content: {
type:String,
required: true
}
},
data() {
return {
}
},
computed: {
durarion() { // 滚动时长
const len = this.content && this.content.length
return len / 5 + 's'
},
repeatNum() { // 计算重复次数
const len = this.content && this.content.length)
return len > 500 ? 2 : (len > 200 ? 3 : 4)
}
}
}
.tip-content {
display: inline-block;
white-space: nowrap;
padding-right: 200px; // 设置每个的间距
color: #333;
line-height: 16px;
}
@keyframes run {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-20%); // 根据实际的个数计算百分比 , 百分比 = 100 / 个数
}
}