CSS / JQuery在hover时侧向滚动文本

我在我运行的网站上有一个Twitter提要。 但是,它会在小屏幕上被切断。 我有一个足够高的栏,可以在1行文字中找到最新的推文。 如果它太长,我希望推文在最后进行椭圆化或淡出。 但是在hover时,我希望文本向左缓慢滑动,从而暴露出隐藏的部分。

当您突出显示标题宽于屏幕的歌曲时,此效果将用于iPod classic。 (我希望你明白我的意思。)

我只是好奇我将如何实现这样的东西? 如何强制文本保持在一行?

这是一个相当简单的方法。 首先,设置一个包含长文本的div:

Here is the long content, long long content. So long. Too long.

您可以使用一些css自动处理截断和省略号:

 div#container { /* among other settings: see fiddle */ width: 200px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } 

如果然后确定内容的原始,未截断的宽度,则可以使用jQuery的.animate()以一致的速度移动该内容 – 即使您在运行时之前不知道文本的长度(如同使用twitter feed的情况)。 这是获得测量的一种有点机械方式:

 var true_width = ( function(){ var $tempobj = $('#container') // starting with truncated text div container .clone().contents() // duplicate the text .wrap('
') // wrap it in a container .parent().appendTo('body') // add this to the dom .css('left','-1000px'); // but put it far off-screen var result = $tempobj.width(); // measure it $tempobj.remove(); // clean up return result; })();

最后,一些动画:

 $('#container').one('mouseenter', function(){ // perhaps trigger once only var shift_distance = true_width - $(this).width(); // how far to move var time_normalized = parseInt(shift_distance / 100, 10) * 1000; // speed $(this).contents().wrap('
').parent() // wrap in div .animate({ left: -shift_distance, right: 0 }, time_normalized, 'linear'); // and move the div within its "viewport" });

无论文本的长度如何,您都将获得每100像素大约一秒的一致速度(根据需要进行调整)。 在mouseleave上重置或倒带内容留作练习。 这种方法有些天真,但可能会给你一些想法。

这是一个有效的例子: http : //jsfiddle.net/redler/zdvyj/

最后,这是我的条目: http : //jsfiddle.net/sdleihssirhc/AYYQe/3/

酷的东西:

  1. 图书馆不可知论者
  2. 使用scrollLeft而不是绝对定位,因此它更平滑,更快速
  3. 使用text-overflow:ellipsis而不是添加任何DOM元素

有一些插件可以做到这一点(例如Remy Sharp: http : //remysharp.com/demo/marquee.html ),但如果你是从头开始构建:

正在滚动的项目需要具有“white-space:nowrap;” (将它保持在一行),“position:absolute”(允许它向左和向右滚动)并包裹在一个相对定位的元素中,该元素具有“overflow:hidden”(使其看起来只有你想要显示的宽度) 。

使用jQuery,您可以使用.animate()在hover事件中从左向右移动滚动项

我在jsfiddle的解决方案或最后,它使用CSS3动画。 我从这里和这里借用了一些想法。 我的想法是让容器div ,即div.s足够宽,以便它可以包含所有文本,从而允许在@keyframes规则中使用left属性的百分比,因此:

 .s { display: inline-block; } .t:hover, .s:hover { width: auto; } 

这是代码:

 .t { white-space: nowrap; position: relative; overflow: hidden; text-overflow: ellipsis; display: block; width: 100%; } .s { display: inline-block; width: 100%; } .t:hover, .s:hover { width: auto; } .s:hover .t { animation: scroll 15s; } .f { width: 100px; background: red; overflow: hidden; } @keyframes scroll { 0% {left: 0px;} 100% {left: -100%;} } 
 
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id impedit accusamus nulla facilis unde sed ipsum maiores adipisci, eius excepturi saepe perspiciatis sequi optio ipsam odio quibusdam quo libero repudiandae.

Steffen Rusitschka写了一个jQuery脚本RUZEE.Ellipsis来做这件事。

你可以看看jRollingNews
使用代码生成器自定义条形并预览结果。

免责声明:我做到了。