用jquery更改文本,无法正确转换

Ken*_*nyV 7 html javascript css jquery

我正在研究文本效果,但过渡并不完全符合我的喜好.

我正在替换一个居中文本行中的单个单词,我将旧单词淡出而新单词淡入,但周围文本"跳转".我已经尝试了一段时间来弄清楚如何通过在边距或宽度上使用动画来以某种方式滑动到它的新位置,但我似乎无法弄明白.

这是我现在所拥有的JSfiddle http://jsfiddle.net/DEk7m/3/

我想要实现的是类似于大标题中所见的内容:https://gumroad.com/

以下是代码:

HTML:

<h1 id="changingtext">This is <span>changing</span> text</h1>
Run Code Online (Sandbox Code Playgroud)

CSS:

h1 {
text-align: center;
font-family: helvetica, arial, sans-serif;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript(使用jQuery):

$(function() {
  var t1 = new Array("changing", "dynamic", "cool");
  var i = 0;
  var tid = setInterval(
      function() {
        $("#changingtext span").animate({'opacity': 0}, 1000, function () {
            $(this).text(t1[i]);
        }).animate({'opacity': 1}, 1000);

        if(i < t1.length -1) 
            i++;
        else i = 0;

      }, 3000 );

});
Run Code Online (Sandbox Code Playgroud)

非常感谢!

mou*_*man 5

您的演示中缺少宽度,看看这个,

HTML

<body>
    <h1><span id="chkWidth" style="display: none;"></span></h1>
    <h1 id="changingtext">This is <span>changing</span> text</h1>
</body>
Run Code Online (Sandbox Code Playgroud)

脚本

$(function() {
  var t1 = new Array("changing", "dynamic", "cool");
  var i = 0;
  var width;
  var tid = setInterval(
      function() {
          $("#changingtext span").animate({'opacity': 0}, 1000, function () {
            $(this).text(t1[i]);
            width = $('#chkWidth').text(t1[i]).width();
            $(this).animate({'opacity': 1, 'width': width}, 1000);
        });

        if(i < t1.length -1) 
            i++;
        else i = 0;

      }, 3000 );

});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/DEk7m/8/

希望这会帮助你.


hit*_*uct 1

动画不透明度宽度

您可以设置一个对象数组以包含接下来出现的每个实例的理想宽度。

var t1 = [ ['changing', '130px'], ['dynamic', '80px'], ['cool','150px'] ],
    i = 0;

var tid = setInterval( function() {

  $("#changingtext span")
  .animate({
    'opacity': 0,
    'width': t1[i][1] },
    500,
    function() {
      $(this).text( t1[i][0] );
    })
  .animate({'opacity': 1}, 1000);

  if(i < t1.length -1) 
    i++;
  else
    i = 0;

}, 3000 );
Run Code Online (Sandbox Code Playgroud)

JSFiddle 上的演示

这是一种有点静态且麻烦的方式,但它应该会让您走上正确的方向。

span您可以通过将单词打印为列表、测量它们的宽度并将它们的宽度添加到数组中来动态地计算出跨度的大小。