鼠标离开时如何消除横向滚动文本空白?需动画结束后加ellipsis类
解决文本滚动复位后再添加省略号类的问题
当前代码在鼠标离开.text元素时,会立刻给元素加上.ellipsis类,同时执行文本滚动回初始位置的动画,这会导致出现不必要的空白。需求是等滚动复位的动画完全结束后,再添加.ellipsis类,避免空白问题。
解决思路
jQuery的animate()方法支持传入回调函数,该函数会在动画执行完成后触发。只需将添加.ellipsis类的操作放到这个回调里,就能实现动画结束后再添加类的效果。
修改后的JavaScript代码
// 鼠标悬停时文本滚动 $(".text").mouseenter(function() { $(this).removeClass("ellipsis"); var maxscroll = $(this).width(); var speed = maxscroll * 15; $(this).animate({ scrollLeft: maxscroll }, speed, "linear"); }); // 鼠标离开时复位滚动并添加省略号 $(".text").mouseleave(function() { $(this).stop(); $(this).animate({ scrollLeft: 0 }, 'slow', function() { // 动画完成后再添加省略号类 $(this).addClass("ellipsis"); }); });
CSS代码(无需修改)
.container { display: flex; flex-direction: column; width: 320px; background: silver; } .text { margin: 5px; border:1px solid; white-space: nowrap; overflow: hidden; font-size: 18px; } .ellipsis { text-overflow: ellipsis; }
HTML代码(无需修改)
<div class="container"> <div class="text">Lorem Ipsum</div> <div class="text ellipsis"> <span>Lorem Ipsum is simply dummy text of the printing</span> </div> <div class="text ellipsis"> <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry</span> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
内容的提问来源于stack exchange,提问作者3Code
相关产品推荐
相关产品推荐

