/** * 超出部分隐藏文字省略。。。 * 鼠标放上显示隐藏文字 * 使用 : 需要溢出隐藏的直接加上指令 v-show-tips 即可 *使用方法<div v-show-tips >{{ name }}</div> * */ export default { mounted(el, binding) { // 获取元素样式 const style = window.getComputedStyle(el) // 创建用于测量的 span 元素 const textSpan = document.createElement('span') Object.assign(textSpan.style, { position: 'absolute', left: '-9999px', fontSize: style.fontSize, fontWeight: style.fontWeight, fontFamily: style.fontFamily, whiteSpace: 'nowrap' // 防止文本换行 }) textSpan.textContent = el.textContent || el.innerText document.body.appendChild(textSpan) // 检查是否需要省略 if (textSpan.offsetWidth > el.offsetWidth) { // 设置省略样式 el.style.overflow = 'hidden' el.style.textOverflow = 'ellipsis' el.style.whiteSpace = 'nowrap' // 添加鼠标移入事件 el.addEventListener('mouseenter', () => { // 创建 tooltip 元素 const tooltip = document.createElement('div') tooltip.classList.add('tooltip') tooltip.textContent = textSpan.textContent // 设置 tooltip 样式 Object.assign(tooltip.style, { position: 'absolute', top: `${el.getBoundingClientRect().top + el.offsetHeight + 10}px`, left: `${el.getBoundingClientRect().left}px`, backgroundColor: 'rgba(0, 0, 0, 0.6)', color: 'white', padding: '10px', borderRadius: '5px', zIndex: '1000', maxWidth: '100%' // 示例值,可以根据需要调整 }) // 将 tooltip 添加到 body document.body.appendChild(tooltip) // 添加鼠标移出事件 tooltip.addEventListener('mouseleave', () => { document.body.removeChild(tooltip) }) // 同时监听原始元素的移出事件,确保在鼠标直接从原始元素移出时也能移除 tooltip el.addEventListener('mouseleave', () => { document.body.removeChild(tooltip) }) }) } // 清理创建的 span 元素 document.body.removeChild(textSpan) }, unmounted(el) { // 清理可能存在的 tooltip 元素(如果有的话) const tooltip = document.querySelector('.tooltip') if (tooltip && tooltip.parentNode === document.body) { document.body.removeChild(tooltip) } } }
vue3 盒子内容多出部分省略,鼠标放上隐藏
最新推荐文章于 2024-08-30 15:24:07 发布