You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.4 KiB
JavaScript

export default {
mounted(el, binding) {
const duration = binding.value?.duration || 4
const delay = binding.value?.delay || 1
const run = () => {
// 1. 找到容器内部所有带 id 的元素
const nodes = [...el.querySelectorAll('#autoScroll')]
// 2. 按 id 分组
const groups = {}
nodes.forEach(node => {
const id = node.id
if (!groups[id]) groups[id] = []
groups[id].push(node)
})
// 3. 每组只判断一次
Object.keys(groups).forEach(id => {
const group = groups[id]
const target = group[0]
const parent = target.parentElement
if (!parent) return
target.style.display = 'inline-block'
target.style.whiteSpace = 'nowrap'
const overflow = target.scrollWidth - parent.clientWidth
if (overflow > 0) {
group.forEach(elm => {
elm.classList.add('auto-scroll-back')
elm.style.setProperty('--scroll-x', `${overflow}px`)
elm.style.animationDuration = `${duration * 2 + delay * 2}s`
})
} else {
group.forEach(elm => {
elm.classList.remove('auto-scroll-back')
})
}
})
}
requestAnimationFrame(() => {
requestAnimationFrame(run)
})
const ro = new ResizeObserver(run)
ro.observe(el)
el.__ro__ = ro
},
unmounted(el) {
el.__ro__?.disconnect()
}
}