容器滑动时text-overflow: ellipsis未生效,如何实现溢出文本隐藏显示省略号?
问题排查与修复方案
text-overflow: ellipsis 实现单行省略效果必须满足三个核心条件,你的代码未完全符合要求,同时存在绝对定位元素遮挡文本的问题,具体修复方案如下:
问题根因
.description类缺少white-space: nowrap强制单行属性,无法触发省略号渲染逻辑- 两个文本容器均未预留右侧操作区的避让空间,绝对定位的
.price和.slide会直接遮挡文本,就算省略号生效也不可见 - 文本容器没有绑定hover状态下的宽度联动,滑出操作区后文本可用宽度缩小,原有内容会被遮挡
修复后代码
CSS代码
.wrapper { position: relative; overflow: hidden; width: 400px; height: 100px; border: 1px solid black; } .description{ overflow:hidden; text-overflow: ellipsis; white-space: nowrap; width: 300px; /* 初始避让右侧100px的price区域 */ margin: 10px 0 0 10px; /* 修正默认边距避免溢出容器 */ transition: width 1s; /* 过渡动画和操作区滑动保持同步 */ } .description2{ white-space: nowrap; overflow:hidden; text-overflow: ellipsis; width: 300px; margin: 10px 0 0 10px; transition: width 1s; } /* hover时操作区占200px宽度,文本宽度对应缩小 */ .wrapper:hover .description, .wrapper:hover .description2 { width: 200px; } .price{ position: absolute; right: 0; bottom: 0; width: 100px; height: 100%; background: green; transition: 1s; } .slide { position: absolute; right: -100px; bottom: 0; width: 100px; height: 100%; background: blue; transition: 1s; } .wrapper:hover .slide { right: 0; } .wrapper:hover .price { right: 100px; }
HTML代码无需修改,和原代码一致即可
<div class="wrapper"> <h4 class="description">Lorem ipsum dolor sit amet, consectetur</h4> <p class="description2"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae nulla </p> <span class="price"></span> <div class="slide"></div> </div>
效果说明
默认状态下文本宽度为300px,超出内容自动显示省略号,不会被右侧绿色价格区域遮挡;hover时操作区滑出,文本宽度同步缩小为200px,超出部分自动隐藏并显示省略号,全程动效和操作区滑动保持一致。
内容的提问来源于stack exchange,提问作者Jysai
相关产品推荐
相关产品推荐

