fontScroll.ts 指令文件
import { Directive } from 'vue'function randomInt(min, max) {return Math.floor(Math.random() * (max - min + 1)) + min;
}
export default {// 可控制滚动速度,默认滚动速度20px/s,最低动画时长2smounted: (el, binding, vNode): void => {el.style.overflow = 'hidden'el.style.whiteSpace = 'nowrap'const speed = binding.value || 20el.__span__ = document.createElement('span')el.__span__.innerHTML = vNode.children[0].childrenel.innerHTML = ''el.appendChild(el.__span__)// 滚动el.isRoll = () => {if (el.__span__.offsetWidth > el.offsetWidth) {const times = Math.max(Number(el.__span__.offsetWidth - el.offsetWidth) / speed,6)let offsetleft = el.__span__.offsetWidth-100;let mymove = `@keyframes myAnimation { 0% { transform: translate(0px, 0); } 100% { transform: translate(-${offsetleft}px, 0);animation-delay: 2s; } }`;const style:any = document.createElement('style');style.setAttribute('type', 'text/css')document.head.appendChild(style)style.sheet.insertRule(mymove, 0)el.__span__.style.float = 'left';let num = randomInt(1,4);console.log(num)el.__span__.style.animation = `myAnimation linear ${times}s ${num}s infinite normal forwards`} else {el.__span__.style.float = 'none'el.__span__.style.animation = 'none'}}el.__observe__ = new ResizeObserver(el.isRoll)el.__observe__.observe(el, { box: 'border-box' })},updated: (el, _, vNode) => {el.__span__.innerText = vNode.children[0].childrenel.isRoll()},unmounted: (el: any): void => {el.__observe__.disconnect()},
} as Directive<any, number>
main.ts 引入&全局注入
import directives from '@/script/utils/fontScrall'app.directive('textRoll',directives)
页面中使用 v-text-roll
<div v-text-roll> 11月27日上午,王思聪现身山东泰安,以北京寰聚商业管理有限公司
董事长身份,出席了泰安某文旅项目签约活动。 </div>
《完》