我正在尝试使用 javascript 函数 width 来获取容器的宽度,并使用它来计算一些滚动文本应该开始滚动的位置(我希望它在黄色框内滚动):
现在,像这样的javascript代码:
alert(yellowBox.width());
alert(yellowBox.innerWidth());
alert(yellowBox.outerWidth());
全部显示,944,但我确定黄色框实际上是 500 的宽度,但我不想使用该值,因为宽度可能会改变。
而且我不确定如何获得盒子的实际宽度。我试过使用yellowBox.offsetWidth()
, 和yellowBox.clientWidth
,但它们不起作用,Web Developer, Web Console plugin for firefox 告诉我“yellowBox.offsetWidth 不是一个函数”,还有“yellowBox.clientWidth 不是一个函数。
这是我的代码:
html:
<div class="container-fluid" style="padding: 5px 20px;">
<div class="well" style="background-color: <?php echo $layout_setting[2][value]; ?>; font-size:large; font-weight:bold;">
<div class="marquee" style="white-space: nowrap; width: 100%; color: <?php echo $layout_setting[7][value] ?>; overflow: hidden; ">
<?php echo $rssContent; ?>
</div>
</div>
</div>
js插件代码:
(function( $ ) {
$.fn.marquee = function(params) {
params = $.extend( {direction : 'left',duration : '2000', delayStart : '0'}, params);
var duration = parseInt(params.duration);
var delay = parseInt(params.delayStart);
var par = $(this);
alert(par.width());
alert(par.innerWidth());
alert(par.outerWidth());
par.wrapInner('<span></span>');
/*I get the same result for width both before and after the line that says `par.wrapInner('<span></span>');*/
alert(par.width());
alert(par.innerWidth());
alert(par.outerWidth());
var parCh = par.children('span');
var leftMargin = parCh.css('margin-left').replace('px', '');
var rightMargin = par.innerWidth() - leftMargin - parCh.width();
function dirRight() {
parCh.css({'margin-left' : '' + leftMargin + 'px'});
//I've determined that `500` is about the width of the yellow box, by changing the line above to:
//`parCh.css({'margin-left' : '' + leftMargin + 500 + 'px'});`
//and seeing where that is the about the value it needs to be to have the left side of the text start out scrolling into the right side of the box
//instead of having the left side of the scrolling text starting at the left side of the yellow box
parCh.animate({'margin-left' : '' + rightMargin + 'px'}, duration, 'linear', function() { dirRight(); });
}
function dirLeft() {
parCh.css({'margin-left' : '' + rightMargin + 'px'});
parCh.animate({'margin-left' : '' + leftMargin + 'px'}, duration, 'linear', function() { dirLeft(); });
}
if (params.direction == 'right') setTimeout(function(){ dirRight() }, delay);
if (params.direction == 'left') {
parCh.css({'margin-left' : '' + rightMargin + 'px'});
setTimeout(function(){ dirLeft() }, delay);
}
$(window).resize(function() { rightMargin = par.innerWidth() - leftMargin - parCh.width(); });
};
}( jQuery ));
以及我调用插件的功能:
function scrollMarquee() {
setInterval("scrollMarquee()", 1000000);
$('.marquee').marquee({'direction' : 'right', 'delayStart' : '0', 'duration' : '1000000'});
}