如果我将固定宽度更改为“自动”,则动画会失真

对于我作为span的框,我希望它们具有自动宽度,以便文本可以完全水平显示。 但是,如果我将其更改为自动,则会损坏我的动画。 默认情况下,宽度值为50px,因此工作正常。

http://jsfiddle.net/31n7r699/

#horizontalScroller > span { position:absolute; width:50px; __width:auto; height:50px; left: -50px; border: 1px solid blue; overflow:hidden; display:inline-block; background:red; } 

您只需要在CSS中进行简单的更改即可。

 #horizontalScroller > span { position:absolute; // make it width auto width:auto; // put it far far far away from the view to prevent the blink thingy at start left: 999px; border: 1px solid blue; background:red; // make it nowrap, this will prevent the span from forcing the text from being displayed in the container white-space: nowrap; // remove this,  are inline-block by default // this do not work also as this is position: absolute; // display: inline-block; } 

更新:

你的解决方案只是工作,因为所涉及的元素具有一致的宽度,当它们具有不一致的宽度时它将会断开,因为当一些句子较短而其他句子较长时它应该是真正意义上的。 要解决此问题,您需要考虑正确定位它们各自的宽度:

 $(document).ready(function() { var container = $("#horizontalScroller"); var children = $(container).children(); var containerW = $(container).width(); // simply the space between them var padding = 10; for (var i = 0; i < children.length; i++) { var item = children[i]; var itemW = $(item).width(); // position the first item with X = container width + padding var X = containerW + padding; // we need to properly position the elements beside each other // specially if they have different widths // i > 0 because there is no sibling on 0 if (i > 0) { // get the element before this var sibling = children[i - 1]; // get the siblings X and W var siblingX = parseInt($(sibling).css("left")); var siblingW = $(sibling).width(); // position this element beside the sibling by: // X = sibling X + sibling W + padding X = siblingX + siblingW + padding; } $(item).css("left", X + "px"); window.horizontalScroller($(item)); } }); 

然后在你的动画回调中,你也应该做这个解决方案:

 $elem.animate({ left: (parseInt(left)-60) }, 900, function () { var currentLeft = parseInt($(this).css("left")); var width = $(this).width(); var container = $(this).parent("#horizontalScroller"); var containerWidth = $(container).width(); if ((currentLeft + width) <= 0) { // instead of putting it at the end of the container // $(this).css("left", (containerWidth + width) + "px"); // we need to put it beside the last element in the list var children = $(container).children(); // get the last item var lastChild = children[children.length - 1]; // get the lastChild X and W var lastChildX = parseInt($(lastChild).css("left")); var lastChildW = $(lastChild).width(); var padding = 20; var X = lastChildX + lastChildW + padding; // position this element beside the last item $(this).css("left", X + "px"); // move this element beside the last item // literally moving the element beside the last item in the DOM to make this solution fully functional $(this).insertAfter(lastChild); } window.horizontalScroller($(this)) }); 

工作小提琴

希望有所帮助,