在前端開發中,如何在元素的懸停狀態下保持寬度不變,同時內容內縮并顯示圖標是一個常見需求。特別是當元素寬度因動態數據變化而變化時,實現這種效果會成為一個挑戰。
例如,我們有一個包含{{data}}的元素,由于data的長度不固定,元素的寬度也會隨之變化。我們希望在鼠標懸停時,元素的總寬度保持不變,同時在元素內部顯示一個圖標,并將data內容向內壓縮,形成如3….
雖然可以使用JavaScript編寫一個組件來實現這一功能,如下所示:
// 在標簽內容每次變化時設置寬度,使標簽具有固定寬度 setWidth() { const c = this.$refs.content; this.width = c.getBoundingClientRect().width; c.style.width = `${this.width}px`; }, // 在標簽內容每次變化時重置寬度,使標簽內容自適應 resetWidth() { this.width = 0; this.$refs.content.style.width = ''; }
然而,這種方法不夠簡潔,并且可能對性能產生影響。實際上,我們可以使用純css更優雅高效地實現這一效果。
假設我們有一個如下的html結構:
立即學習“前端免費學習筆記(深入)”;
ABCabcdsfes<i class="texticon">?</i>DEFGHIGK
對應的CSS樣式如下:
.fonttext { position: relative; display: inline-block; overflow: hidden; vertical-align: bottom; border: 2px dashed red; box-sizing: border-box; border-radius: 4px; } .texticon { position: absolute; width: 20px; height: 100%; background-color: #fff; border: 2px dashed red; font-style: normal; right: -21px; border-left: none; cursor: pointer; border-radius: 4px; top: -2px; display: inline-table; } .texticon:hover { background-color: #2d77ed; } .fonttext:hover { overflow: visible; border-top-right-radius: 0; border-bottom-right-radius: 0; border-right-color: transparent; } .fonttext:hover .texticon { border-top-left-radius: 0; border-bottom-left-radius: 0; border-left-color: transparent; }
通過上述CSS,我們可以在鼠標懸停到.fonttext元素上時,保持元素的寬度不變,同時顯示.texticon圖標,并使內容向內壓縮形成省略號的效果。這種方法不僅簡潔高效,還能更好地利用CSS的特性來實現動態效果。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END