javascript 动画改变字宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20695877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:02:12  来源:igfitidea点击:

Animate changing words width

javascriptjqueryhtmlcssanimation

提问by Josue Espinosa

I have a sentence where I fade in one word and replace it with another from an array. However, since the words all vary in length, the sentence width abruptly changes and it results in a choppy transition.
How can I animate the width change? I tried adding a transition to the container of the sentence in css but that didn't work. I applied the transition as 1.5s all linear, so it should be animating the width as well as everything else whenever there is change. Any ideas?

我有一个句子,我淡出一个词,然后用数组中的另一个词替换它。但是,由于单词的长度各不相同,因此句子宽度会突然发生变化,从而导致断断续续的过渡。
如何为宽度变化设置动画?我尝试在 css 中向句子的容器添加过渡,但这没有用。我将过渡应用为1.5s all linear,因此只要有变化,它就应该为宽度以及其他所有内容设置动画。有任何想法吗?

$(function() {
  var hello = ['dynamic', 'a', 'aklsjdlfajklsdlkf', 'asdf'];
  var used = ['dynamic'];
  var greeting = $('#what');
  var item;

  function hey() {

    item = hello[Math.floor(Math.random() * hello.length)];
    if (hello.length != used.length) {
      while (jQuery.inArray(item, used) != -1) {
        item = hello[Math.floor(Math.random() * hello.length)];
      }
      used.push(item);
    } else {
      used.length = 0;
      item = hello[Math.floor(Math.random() * hello.length)];
      used.push(item);
    }
    greeting.html(item);
    greeting.animate({
      "opacity": "1"
    }, 1500);
  }

  window.setInterval(function() {
    greeting.animate({
      "opacity": "0"
    }, 1500);
    setTimeout(hey, 1500)
  }, 5000);

});
#sentence {
  transition: 1.5s all linear;
}

#what {
  font-style: italic;
  text-decoration: underline;
  color: red;
}
<p id="sentence">
  This is a sentence that has <span id="what">dynamic</span> text that alters width.
</p>

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

EDIT: Sorry if I was unclear, I only want to fade out the word, not the entire sentence. I'm trying to animate the width to fit the new word. I don't want to change/add any elements, just solve with the current tags in place.

编辑:对不起,如果我不清楚,我只想淡出这个词,而不是整个句子。我正在尝试为宽度设置动画以适应新单词。我不想更改/添加任何元素,只需使用当前标签解决即可。

回答by Roko C. Buljan

Fade animate text with jQuery by Roko C.B.

Roko CB 使用 jQuery 淡化动画文本

function dataWord () {

  $("[data-words]").attr("data-words", function(i, d){
    var $self  = $(this),
        $words = d.split("|"),
        tot    = $words.length,
        c      = 0; 

    // CREATE SPANS INSIDE SPAN
    for(var i=0; i<tot; i++) $self.append($('<span/>',{text:$words[i]}));

    // COLLECT WORDS AND HIDE
    $words = $self.find("span").hide();

    // ANIMATE AND LOOP
    (function loop(){
      $self.animate({ width: $words.eq( c ).width() });
      $words.stop().fadeOut().eq(c).fadeIn().delay(1000).show(0, loop);
      c = ++c % tot;
    }());
    
  });

}

// dataWord(); // If you don't use external fonts use this on DOM ready; otherwise use:
$(window).on("load", dataWord);
p{text-align: center;font-family: 'Open Sans Condensed', sans-serif;font-size: 2em;}

/* WORDS SWAP */
[data-words]{
  vertical-align: top;
  position: static;
}
[data-words] > span{
  position: absolute;
  color: chocolate;
}
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  We provide
  <span data-words="code|solutions|design"></span>
  for your business.
</p>

<p>
  You ordered
  <span data-words="1|3|28"></span>
  <b>big</b>
  <span data-words="salad|macs|chips"></span>
</p>

回答by Ringo

When you set new word for your sentence, you can save #what width and then make an animation with this width too. Like this:

当你为你的句子设置新词时,你可以保存#what width,然后也用这个宽度制作动画。像这样:

// declare as global variable and update when you set new word
var width = greeting.css('width'); 
// animation
greeting.animate({
            "opacity": "0", "width": width
        }, 1500, function(){
        });

回答by Aditya Singh

Try this out:- http://jsfiddle.net/adiioo7/c8fFU/13/

试试这个:- http://jsfiddle.net/adiioo7/c8fFU/13/

You can update the sentence effect depending upon your requirement. Currently it is using fadein/fadeout.

您可以根据需要更新句子效果。目前它正在使用淡入/淡出。

JS:-

JS:-

$(function () {
    var hello = ['jupiter', 'a', 'aklsjdlfajklsdlkf', 'asdf'];
    var used = ['jupiter'];
    var greeting = $('#what');
    var item;
    var sentence = $('#sentence');

    function hey() {
        item = hello[Math.floor(Math.random() * hello.length)];
        if (hello.length != used.length) {
            while (jQuery.inArray(item, used) != -1) {
                item = hello[Math.floor(Math.random() * hello.length)];
            }
            used.push(item);
        } else {
            used.length = 0;
            item = hello[Math.floor(Math.random() * hello.length)];
            used.push(item);
        }
        greeting.html(item);
        greeting.animate({
            "opacity": "1"
        }, 1500);

        sentence.fadeIn(1500);
    }

    window.setInterval(function () {
        sentence.fadeOut(1500);
        greeting.animate({
            "opacity": "0"
        }, 1500);
        setTimeout(hey, 1500);
    }, 5000);

});

回答by Willem

I have had the same problem and went with a different approach, not fading but typing: jsfiddle demo

我遇到了同样的问题,并采用了不同的方法,不是褪色而是打字:jsfiddle demo

function type($el, text, position) {
    if (text.length >= position) {
        var rchars = 'qbvol'; // typo chars
        if (position % 3 == 0 && Math.random() > .85) { // insert typo!
            var typo;
            var chr = text.substr(position, 1);
            if (chr == chr.toUpperCase()) { typo = chr.toLowerCase(); }
            else { typo = rchars.substr(Math.floor(Math.random() * rchars.length), 1); }
            $el.text(text.substring(0, position - 1) + typo + '_');
            setTimeout(function() { type($el, text, position - 1); }, 200)
        }
        else {
            $el.text(text.substring(0, position) + '_');
            setTimeout(function() { type($el, text, position + 1); }, 150)
        }
    }
    else {
        setTimeout(function() { $el.text(text); }, 400)
    }
}

It basically inserts your new text on the page, with a nice caret and typo to make it look like someone is typing it.

它基本上是在页面上插入你的新文本,用一个很好的插入符号和错字来让它看起来像是有人在打字。