最近写大屏项目,轮播表的列头有部分字段较长,要求循环滚动,没有被隐藏的不做滚动处理
首先调整样式,overflow: hidden隐藏的同时将多余的用省略号,需要加text-overflow: clip将省略号还原
overflow: hidden
text-overflow: clip
因列头是通过接口获取的,需要用js动态的判断字体长度是否超出外层盒子长度,另js使用keyframe较麻烦,所以选择transition而没有使用animation
setTransition() {
//每个列头的类名为header-item
const dom = [...document.getElementsByClassName('header-item')] as HTMLElement[]
dom.forEach((item: any) => {
//分别获取每个列头的宽度和列头内字体的宽度
const fatherWidth = item.getBoundingClientRect().width
const childWidth = item.children[0].getBoundingClientRect().width
/*重置每个列头内字体的transition相关样式,ontransitionend为过渡动画结束后执行的函
数*/
item.children[0].style.transition = 'none'
item.children[0].style.left = `0px`
item.children[0].ontransitionend = null
//判断字体长度大于父元素长度即给字体添加过渡样式
if (childWidth > fatherWidth) {
item.children[0].style.transition = 'left 3s 2s'
item.children[0].style.left = `${fatherWidth - childWidth}px`
item.children[0].ontransitionend = () => {
//过渡动画结束后2秒执行去掉过渡样式并调整字体位置
setTimeout(() => {
item.children[0].style.transition = 'none'
item.children[0].style.left = `0px`
//重置字体样式后1秒重新给字体田间过渡样式
setTimeout(() => {
item.children[0].style.transition = 'left linear 3s 2s'
item.children[0].style.left = `${fatherWidth - childWidth}px`
}, 1000)
},2000)
}
}
})
}