天天看点

vue内容横向循环滚动_vue文字横向滚动公告

需求

最新项目需要一个文字横向滚动效果,

vue 文字横向无缝走马灯组件

写的很详细,记录下来,广播出去。

解决方案

1、 HTML

先建一个div层作为公告显示区,里面包裹一个公告列表(ul);

2、 CSS

每条公告信息(li)的margin必须设置‘px’单位,否则要转换,后面js中回到起点还要用到这个值。

body,div,html,img,li,ul{margin:0;padding:0;border:0}

li{list-style:none}

.advert-top{position:relative;display:flex;width:100%;height:.88rem;background:linear-gradient(270deg,rgba(80,175,255,1) 0,rgba(13,132,248,1) 48%,rgba(55,159,248,1) 86%,rgba(81,176,255,1) 100%);color:#fff;font-size:.26rem;align-items:center}

.ico-horn{display:flex;width:.88rem;height:.88rem;justify-content:center;align-items:center}

.ico-horn>img{width:.32rem;height:.32rem}

.marquee-wrap{position:relative;display:flex;overflow:hidden;width:100%;height:100%}

.marquee-box{position:absolute;top:50%;display:flex;white-space:nowrap;transform:translateY(-50%)}

.marquee-list{margin-right:10px}

.marquee-list span{padding:0 .04rem;color:#ffe17b;font-weight:700}

3、 JavaScript

var vm = new Vue({

el: '#app',

data: {

ico_horn: 'https://img.alicdn.com/tfs/TB1zwftaPrguuRjy0FeXXXcbFXa-16-16.png',

message: "全球新冠肺炎确诊病例超45万,死亡人数破2万!",

},

mounted: function () {

// 延时滚动

setTimeout(() => {

this.runMarquee()

}, 1000)

},

methods: {

runMarquee() {

// 获取文字 计算后宽度

var width = document.getElementById('marquee').getBoundingClientRect().width,

marquee = document.getElementById('marquee-box'),

disx = 0; // 位移距离

//设置位移

setInterval(() => {

disx--; // disx-=1; 滚动步长

if (-disx >= width) {

disx = 10; // 如果位移超过文字宽度,则回到起点 marquee-list的margin值

}

// marquee.style.transform = 'translateX(' + disx + 'px)'

marquee.style.left = disx + 'px'

}, 30) //滚动速度

}

}

});

// JavaScript Document

(function px2rem(doc, win) {

var docEl = doc.documentElement,

resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',

recalc = function () {

var clientWidth = docEl.clientWidth;

if (!clientWidth) return;

docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';

};

if (!doc.addEventListener) return;

// 窗口大小发生变化,初始化

win.addEventListener(resizeEvt, recalc, false);

doc.addEventListener('DOMContentLoaded', recalc, false);

//防止在html未加载完毕时执行,保证获取正确的页宽

setTimeout(function () {

px2rem(doc, win);

}, 200);

})(document, window);