如何实现元素hover时宽度不变,内容内缩并显示icon?

如何实现元素hover的时候宽度不变,动态内缩?
如果有一个元素,它的宽度随着传入的数据增长而增长
<span>{{data}}</span>,宽度不能固定的原因是因为,data不定长。
我希望实现的是鼠标hover在这个元素上面的时候,整个span的长度不变(因为页面不只一个这种类型的span,不希望页面大幅度改变),span里渲染出一个icon,data数据向内挤压生成省略号,类似于<span>3....<icon/></span>

我的尝试是通过js的方式,写一个组件,通过以下的方法配合省略溢出做的

// 作用是每次标签内容变化时,设置宽度,让标签得到固定宽度
        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或者其他更加合理的方法
效果如下:
image.png
hover状态下:
image.png

阅读 318
2 个回答

GIF(1).gif

<div>
      ABC<span class="fonttext">abcdsfes<i class="texticon">😂</i></span
      >DEFGHIGK
    </div>
.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;
}
/* 省略号 */
/* .fonttext::before {
  content: '...';
  position: absolute;
  width: 10px;
  height: 100%;
  right: -10px;
  background-color: white;
} */
/* .fonttext:hover::before {
  right: 0px;
} */
  1. 借助js在数据变化后动态设置容器的宽度
  2. 纯css 使用伪元素 (icon无法交互)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题