如何使用CSS实现元素在hover时保持宽度不变并显示图标?

在前端开发中,如何在元素的悬停状态下保持宽度不变,同时内容内缩并显示图标是一个常见需求。特别是当元素宽度因动态数据变化而变化时,实现这种效果会成为一个挑战。

例如,我们有一个包含{{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的特性来实现动态效果。

如何使用CSS实现元素在hover时保持宽度不变并显示图标?

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享