| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- // v-ellipsis.ts
- import { createApp, ref } from 'vue'
- import 'uview-plus/index.scss' // 若使用 uView Plus,需要导入
- export default {
- mounted(el: HTMLElement, binding: any) {
- const { value } = binding
- const line = value?.lines ?? 1
- const content = value?.content ?? el.innerText
- // 省略号默认样式
- el.style.display = '-webkit-box'
- el.style.webkitBoxOrient = 'vertical'
- el.style.overflow = 'hidden'
- el.style.textOverflow = 'ellipsis'
- el.style.webkitLineClamp = String(line)
- el.style.cursor = 'pointer'
- el.style.wordBreak = 'break-all'
- let pressTimer: any = null
- // 创建 u-popup 的 Vue 子应用
- const popupApp = createApp({
- setup() {
- const show = ref(false)
- const position = ref({ top: 0, left: 0 })
- return { show, position, content }
- },
- template: `
- <u-popup
- v-model="show"
- mode="center"
- :custom-style="{
- position: 'absolute',
- top: position.top + 'px',
- left: position.left + 'px',
- background: '#333',
- color: '#fff',
- padding: '12px',
- borderRadius: '8px',
- maxWidth: '80vw',
- fontSize: '14px',
- lineHeight: '1.6',
- }"
- :mask="false"
- >
- {{ content }}
- </u-popup>
- `,
- })
- const container = document.createElement('div')
- document.body.appendChild(container)
- const popupInstance = popupApp.mount(container) as any
- const showPopup = (event: MouseEvent | TouchEvent) => {
- if (!popupInstance?.position || !popupInstance?.show) return
- const rect = el.getBoundingClientRect()
- popupInstance.position.top = rect.top - 10
- popupInstance.position.left = rect.left + rect.width / 2
- popupInstance.show = true
- }
- const hidePopup = () => {
- if (popupInstance?.show !== undefined) popupInstance.show = false
- }
- // PC hover 事件
- el.addEventListener('mouseenter', showPopup)
- el.addEventListener('mouseleave', hidePopup)
- // mobile 长按显示
- el.addEventListener('touchstart', (e) => {
- pressTimer = setTimeout(() => showPopup(e), 600)
- })
- el.addEventListener('touchend', () => {
- clearTimeout(pressTimer)
- hidePopup()
- })
- el.addEventListener('touchmove', () => {
- clearTimeout(pressTimer)
- hidePopup()
- })
- el._ellipsis_destroy = () => {
- popupApp.unmount()
- container.remove()
- el.removeEventListener('mouseenter', showPopup)
- el.removeEventListener('mouseleave', hidePopup)
- }
- },
- unmounted(el: any) {
- el._ellipsis_destroy && el._ellipsis_destroy()
- },
- }
|