JavaScript - Как оживить изменение ширины замещенных слов в середине предложения

У меня есть предложение, в котором одно слово исчезает и заменяется другим словом в массиве. Однако, поскольку слова все различаются по длине, ширина предложения резко изменяется, и она выглядит изменчивой. Как я могу анимировать ширину? Я попытался добавить переход к контейнеру предложения в css, но это не сработало. Я применил переход как 1.5s all linear, поэтому он должен анимировать ширину, а также все остальное, когда есть изменения. Любые идеи?

JSFiddle

ИЗМЕНИТЬ: Извините, если я не понял, я хочу только погасить слово, а не все предложение. Я пытаюсь оживить ширину, чтобы соответствовать новому слову. Я не хочу изменять/добавлять какие-либо элементы, просто решаясь с текущими тегами на месте.

Ответы

Ответ 1

Fade animate text with jQuery by Roko C.B.

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>

Ответ 2

Когда вы устанавливаете новое слово для своего предложения, вы можете сохранить # ширину, а затем сделать анимацию с этой шириной. Вот так:

// 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(){
        });

Ответ 3

Попробуйте следующее: - http://jsfiddle.net/adiioo7/c8fFU/13/

Вы можете обновить эффект предложения в зависимости от вашего требования. В настоящее время используется fadein/fadeout.

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);

});

Ответ 4

Не хвастаться, но...

Лучший, который вы увидите

CSS

span {
    float: left;
}
#what {
    margin: 0 3px;
}

HTML:

<span class="cf">hello this is a sentence </span><span id="what" class="cf">jupiter</span><span class="cf"> that changes like this:</span>

JavaScript:

$(function () {
    var hello = ['jupiter', 'a', 'aklsjdlfajklsdlkf', 'asdf'];
    var used = ['jupiter'];
    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.text(item);
        greeting.animate({
            "width": "toggle",
                "opacity": 1
        }, 1500);
    }

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

});

Ответ 5

У меня была такая же проблема, и я пошел с другим подходом, а не затухал, но набрал: 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)
    }
}

Он в основном вставляет ваш новый текст на странице с красивой чертой и опечаткой, чтобы он выглядел так, как будто кто-то печатает его.