Rotating text with Javascript

独自空忆成欢 提交于 2019-12-05 05:35:34

A simple example using jQuery
is by storing the desired looping / swapping words into the data-* attribute:

$("[data-words]").attr("data-words", function(i, words) {

    var $self = $(this).text(""),
        words = words.split("|"),
        tot   = words.length,
        c     = 0; 

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

    var $words = $self.find("span");

    (function loop(){
      $self.animate({ width: $words.eq( c ).width() });
      $words.stop().fadeOut().eq(c).fadeIn().delay(1000).show(0, loop);
      c = ++c % tot;
    }());
    
});
/* DATA-WORDS Loop/swap words in sentence */
[data-words] {
  vertical-align: top;
  position: static;
}
[data-words] > span {
  display: none;
  position: absolute;
  color: #0bf;
}
<p>
  This is <span data-words="some|an interesting|some longer">some</span> text
</p>

<p>
  Say <span data-words="hi|wow">hi</span> to <span data-words="Javascript|Stack Overflow">mom</span>
</p>


<script src="//code.jquery.com/jquery-3.1.0.js"></script>

  • The | -delimited words will be converted to Array and finally to child <span> elements
  • Such span elements need to be absolutely positioned inside the parent span
  • jQuery will than init a recursive loop, calculate the next word width, and animating it (fade + width)

How about jQuery's animate() function? http://api.jquery.com/animate/

You can trigger an animation for each word in the array. Here's an idea, you will have to figure out how populate the variables hasMoreWordsInTheArray and nextWordInTheArray:

function animateParagraphTag(word) {
    if(hasMoreWordsInTheArray) {
        //some special code to calculate the best width based on the word's length (theNewWidthValue)
        $('p').animate(
            { width: theNewWidthValue },
            "fast",
            animateParagraphTag(nextWordInTheArray)
        );
    }
}

You will have to calculate the width based on the length of the words and place that within the parameters of the animation, then, once the p tag finishes the expansion/contraction accordingly, it will trigger the callback function, you can then move on to the next element (word) of the array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!