需求是在可视化页面中,顶部标题如果很长,显示不完全情况下,需要从右向左滚动,这里是在vue中实现,可根据实际情况修改
1,html代码,第一个span是需要显示标题,第二个是,如果标题过长,实现无痕连接滚动
// 两个span标签里面都放一个span空标签是为了滚动的时候,中间出现一段距离,效果更好,当isShowIntval为false时,即不需要滚动,所以第一个span标签里的span不需要显示,标题就会居中显示
<div class="topStyle">
<div ref="outDiv" class="outDiv">
<p class="scrollP">
<span class="topTiele" ref="spanWid"><span style="display: inline-block;width: 40px" v-show="isShowIntval"></span>{{roomTitle}}</span>
<span class="topTiele" ref="spanWid1" v-show="isShowIntval"><span style="display: inline-block;width: 40px"></span>{{roomTitle}}</span>
</p>
</div>
</div>
2,css代码
// 相对于最外层的标签定位,title.png图片是显示标题的限制,即标题只能在该图片中显示,超出图片宽度就会滚动显示
.topStyle {
position: absolute;
top: 0;
width: 100%;
height: 97px;
text-align: center;
line-height: 97px;
background: url("../assets/trainvisual/title.png") no-repeat center center;
background-size: 100% 100%;
}
// 设置标题可显示的宽度
.outDiv {
width: 19%;
height: 97px;
text-align: center;
line-height: 80px;
overflow: hidden;
margin: 0 auto;
}
.scrollP {
white-space: nowrap;
text-align: center;
}
.topTiele {
font-size: 30px;
font-weight: 700;
background-image: -webkit-linear-gradient(bottom, #8AF9F9, #5AFCF0);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-family: Microsoft YaHei;
display: inline-block;
}
3,js
methods: {
// 标题是否需要滚动
marqueeFun() {
clearInterval(this.setIntval);
this.setIntval = null;
// this.$refs.spanWid.offsetWidth 只是获取当前元素宽度, this.$refs是vue里面dom元素写法,可修改
if (this.$refs.spanWid.offsetWidth >= this.$refs.outDiv.offsetWidth) {
this.isShowIntval = true;
this.setIntval = setInterval(() => {
this.marquee();
}, 40);
} else {
this.isShowIntval = false;
if (this.setIntval) {
clearInterval(this.setIntval);
this.setIntval = null;
}
}
},
marquee() {
if (this.$refs.outDiv) {
if (this.$refs.outDiv.scrollLeft - this.$refs.spanWid1.offsetWidth >= 0) {
this.$refs.outDiv.scrollLeft -= this.$refs.spanWid.offsetWidth;
} else {
this.$refs.outDiv.scrollLeft++;
}
}
},
},
mounted() {
let _this = this;//赋值vue的this
_this.marqueeFun(); // 直接调用
},
备注:html中结构不可更改
效果:
title.png