前言 在工作中我們經常會遇到,文字過多,需要用省略號,並且滑鼠hover的時候 還需要 顯示全部的文字的需求。 正文 如何得知這個是否溢出呢?關鍵詞:clientWidth 和scrollWidth: 代碼奉上: 重點坑: 有省略號的標簽,我們使用了overflow:hidden來實現了,那麼這個就 ...
前言
在工作中我們經常會遇到,文字過多,需要用省略號,並且滑鼠hover的時候 還需要 顯示全部的文字的需求。
正文
- 文字過多需要用省略號的實現:上代碼啦
.ellipsis { width: 100%; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display: inline-block //塊級標簽不需要 }
-
如何得知這個是否溢出呢?關鍵詞:clientWidth 和scrollWidth: 代碼奉上:
// 我是在react中實現 componentDidMount () { // 在did mount 中判斷是否溢出 const node = this.ref.current // 判斷的dom節點,使用ref const clientWidth = node.clientWidth const scrollWidth = node.scrollWidth if (clientWidth < scrollWidth) { this.setState({ // 把是否溢出的狀態存在state中,之後從state中拿值使用 overflow: true }) } } // 在普通js中實現,方法一樣,取到dom,判斷clientWidth 和scrollWidth
- 判斷完溢出,一般會需要處理,我這裡的需求是hover時候再顯示全部。方法兩種,第一,使用偽類,第二,包裹一個標簽,該標簽hover時候顯示。
重點坑: 有省略號的標簽,我們使用了overflow:hidden來實現了,那麼這個就是一個BFC,hover時候顯示的提示框,超出bfc的就顯示不了了。。。
方法一 : 偽類實現:代碼上html
<span className={`${styles.detail} ${styles.ellipsis}`} ref={this.departmentRef} data-customer={overflow ? department : null}>{department}</span> // 關註data-customer 屬性,這個屬性在有溢出時候賦值,無溢出時候為null。 還記得ref的作用不?就是第二步中確定是否溢出用的。
.ellipsis { // 第一步溢出的代碼 display: inline-block; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; width: 255px; } .ellipsis[data-customer]:hover::after { // 關鍵代碼,偽類實現 content: attr(data-customer); position: absolute; background: #F2F2F2; border: 1px solid #E5E5E5; box-shadow: 0 2px 4px 0 rgba(56,62,71,0.10); border-radius: 2px; padding: 2px 6px; font-size: 13px; color: #202332; top:106px; // 設置位置 left: 10px; // 設置位置 max-width: 90%; word-break: break-word; // 如果一個單詞太長,則截斷 CSS 屬性word-break
指定了怎樣在單詞內斷行。 white-space: normal;// 可以換行white-space
CSS 屬性是用來設置如何處理元素中的空白。 }
方法二:在hover標簽A 內部再包裹一個標簽B,B標簽在hoverA時顯示。代碼走你
<span ref={this.ref} style={{display: 'inline-block'}} className={overflow ? 'overFlowText' : ''}>
{tableTitle} {overflow ? (<span className='overflowSpan'>{tableTitle}</span>) : null} </span> // 關鍵代碼是那個三元~
.overflow{ position: relative } .overflow .overflowSpan { display: none } .overflow:hover .overflowSpan{ display: block; position: absolute; top: 10px;
left: 0px;
}
參考鏈接: https://stackoverflow.com/questions/2011142/how-to-change-the-style-of-the-title-attribute-inside-an-anchor-tag