Jquery Marquee的动态内容 – 动态宽度也是?

我正在将数据库中的动态内容添加到我在网上找到的选框中。 问题是 – 内容长度变化很大,脚本需要一组静态宽度才能正常工作。 我需要找出一种方法来在我拉动内容时生成宽度,或者让脚本自动生成项目的宽度。 这是我在这里发现的非常重要的脚本。 这是一个JSFiddle ,看看它是如何工作的。

对于那些不喜欢JSFiddle的人来说,这里有一些简单的html / css

This runs differently than the ticker for some reason. It's highly annoying in my personal opinion.

test1
This is Test 2
test3
This is test number 4

CSS

 .event{float: left;} /* Add width and it will run, sorta fine .event{width:100px;} */ 

jQuery的

 (function($) { $.fn.textWidth = function(){ return $(this).width(); }; $.fn.marquee = function(args) { var that = $(this); var $textWidth = that.textWidth(), offset = that.width(), width = offset, css = { 'text-indent' : that.css('text-indent'), 'overflow' : that.css('overflow'), 'white-space' : that.css('white-space') }, marqueeCss = { 'text-indent' : width, 'overflow' : 'hidden', 'white-space' : 'nowrap' }, args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args), i = 0, stop = $textWidth*-1, dfd = $.Deferred(); function go() { if (that.data('isStopped') != 1) { if(!that.length) return dfd.reject(); if(width == stop) { i++; if(i == args.count) { that.css(css); return dfd.resolve(); } if(args.leftToRight) { width = $textWidth*-1; } else { width = offset; } } that.css('text-indent', width + 'px'); if(args.leftToRight) { width++; } else { width--; } } setTimeout(go, 10); }; if(args.leftToRight) { width = $textWidth*-1; width++; stop = offset; } else { width--; } that.css(marqueeCss); that.data('isStopped', 0); that.bind('mouseover', function() { $(this).data('isStopped', 1); }).bind('mouseout', function() { $(this).data('isStopped', 0); }); go(); return dfd.promise(); }; })(jQuery); $('h1').marquee(); $('#ticker').marquee();​ 

我想到的第一件事是在生成选取框之前获取每个列表项的宽度,并将宽度放入内联。 我无法弄清楚如何做到这一点,经过一段时间的玩弄,我放弃了。 这是它所在网站的链接 – 内容通过ajax添加。 大帐篷位于顶部。 稍后我会删除链接。 关于我应该做什么的建议?

只是一个想法,我没有看到你添加动态部分的代码,但它们是否必须在

标签内? 你能用.append()吗?

就像是:

 $('#ticker').append(response.data); //or whatever the variable would be 

所以基本上它只是将文本添加到该div而不是单独的div。 在添加所有数据之前,您可能不需要开始滚动,以便使用选框插件来补偿新添加的文本。

要么

以下是您可以使用的一些代码,可以解决您的初始问题:

将此函数添加到您的代码中:

 $.fn.textWidthTrue = function(){ var html_org = $(this).html(); var html_calc = '' + html_org + ''; $(this).html(html_calc); var width = $(this).find('span:first').width(); $(this).html(html_org); return width; }; 

如下所示: 计算文本宽度

然后添加:

 $('#ticker').find('.event').each(function(i){ // set the width correctly $(this).width($(this).textWidthTrue()); }); 

JSFiddle: http : //jsfiddle.net/NYQEL/12/