使用JavaScript平滑地更改文本 [英] Smoothly changing text with JavaScript

查看:56
本文介绍了使用JavaScript平滑地更改文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个着陆页,其中一个短语随着选择的单词不断变化。例如,

I'm making a landing page where a phrase is constantly changing with select words. For instance,


为客户设计更好的网站

Design better websites
made for clients.

将第一个或最后一个单词切换为

will switch the first or last word to become


开发更好的网站
b $ b为客户制作。

Develop better websites
made for clients.

然而,由于开发是一个比设计更大的词,其余的文字最终被推开而没有顺利过渡。请记住,这是一个多行句子,它是居中的。

However, since "Develop" is a larger word than "Design", the rest of the text ends up getting pushed around without smoothly transitioning. Keep in mind, this is a multi-line sentence, and it is centered.

var first  = ['Create','Design','Develop'];
var second = ['you','clients','artists','us'];
var i = 0;
var j = 0;
var maxfirst  = first.length - 1;
var maxsecond = second.length - 1;

function delay() {
    $('#intro').velocity("transi1ion.slideUpIn", 1250);
    setInterval(firstwordchange, 400);
    setInterval(secondwordchange, 500);
}

function firstwordchange() {
    if (i < maxfirst) i++; else i = 0;

    $('#firstword').velocity("transition.slideUpOut", 300);

    setTimeout(function () {
        $('#firstword').text(first[i]);
    }, 200);

  $('#firstword').velocity("transition.slideUpIn", 300);
}

function secondwordchange() {
    if (j < maxsecond) j++; else j = 0;

    $('#secondword').velocity("transition.slideUpOut", 300);

    setTimeout(function () {
        $('#secondword').text(second[j]);
    }, 200);

    $('#secondword').velocity("transition.slideUpIn", 300);
}

setTimeout(delay, 700);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.1.0/velocity.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.1.0/velocity.ui.min.js"></script>
<div id="intro">
    <span id="firstword" class="introchange">Create</span>
    better websites made for
    <span id="secondword" class="introchange">you</span>.
</div>

如何顺利地进行内部的,不变的文本转换?

How can I make the inner, non-changing text transition smoothly?

这里的实际网站

推荐答案

我将写一篇关于将如何做

I'm going to write an outline of how I would do did it:


  1. 使用默认初始值为更改单词和静态定位渲染句子。

  2. 还使用可见性隐藏其他单词变体:隐藏所以您可以确定他们的尺寸。

  3. 绝对化每个句子部分。从这一点开始,一切都将被绝对定位,所以如果你周围有一个很好的定位环境(通常在父母的位置:相对上完成),这是最好的。

  4. 测量每个句子部分,包括更改单词和固定句子部分的宽度,包括隐藏的部分。

  5. 更改单词时计算旧尺寸和旧尺寸之间的差异新的。基于这些差异,使用一些非常简单的数学来查看应该向左或向右移动多少部分并在它们上应用水平翻译(当然还要为翻译设置动画 - 可能只是为了你想要左/右移动,也许你想要其他改变单词的效果)。

  1. Render the sentence using default initial values for the changing words and static positioning.
  2. Also render the other word variants with visibility: hidden so that you can determine their sizes.
  3. Absolutize every sentence part. From this point on everything will be absolutely positioned so it's best if you have a nice positioning context around it (usually done with position: relative on the parent).
  4. Measure every sentence part, both changing words and fixed sentence parts widths, including the hidden ones.
  5. When changing the words compute the differences between the old sizes and the new ones. Based on those differences, use some very simple Math to see how much parts should move left or right and apply a horizontal translation on them (and of course animate the translation - possibly just for what you want moving left/right, maybe you want other effects for the changing words).

演示:

var first = ['Create','Cut','Reticulate'];
var second = ['you','clients','artists','us'];
var firstM = [], secondM = [], el;

var $first = $('.the-first'); 
var $second = $('.the-second'); 
var $container = $('#container');

// init static //    
$first.text(first[0]);
$second.text(second[0]);

// create measurables //
for(var i = 0; i < first.length; i++){
    el = $('<div class="measurable">' + first[i] + '</div>');
    $container.append(el);
    firstM.push(el.width());
}
for(var i = 0; i < second.length; i++){
    el = $('<div class="measurable">' + second[i] + '</div>');
    $container.append(el);
    secondM.push(el.width());
}

// absolutize //
var positions = [];
$('#container > span').each(function(){
    positions.push($(this).position());
});
$('#container > span').each(function(){
    var pos = positions.shift();
    $(this).css({
        position: 'absolute',
        left: pos.left,
        top: pos.top
    });
});

// remember initial sizes //
var firstInitialWidth = $first.width();
var secondInitialWidth = $second.width();

// loop the loop //
var activeWordsIndex = 0;
setInterval(function(){
    activeWordsIndex++;
    var firstIndex = activeWordsIndex % first.length;
    var secondIndex = activeWordsIndex % second.length;
    
    $first.text( first[firstIndex] );
    $second.text( second[secondIndex] );
    
    var firstLineOffset = (firstM[firstIndex] - firstInitialWidth) / 2;
    var secondLineOffset = (secondM[secondIndex] - secondInitialWidth) / 2;
   
    $('.static.first').css({
        transform: 'translateX(' + firstLineOffset + 'px)'
    });
    $('.static.second').css({
        transform: 'translateX(' + (-secondLineOffset) + 'px)'
    });
    
    $first.css({
        transition: 'none', 
        transform: 'translate(' + (-firstLineOffset) + 'px, -30px)',
        opacity: '0'
    });
    setTimeout(function(){
        $first.css({
            transition: 'all 1s ease',
            transform: 'translate(' + (-firstLineOffset) + 'px, 0px)',
            opacity: '1'
        });
    }, 50);
    
    $second.css({
        transition: 'none', 
        transform: 'translate(' + (-secondLineOffset) + 'px, 30px)',
        opacity: '0'
    });
    setTimeout(function(){
        $second.css({
            transition: 'all 1s ease',
            transform: 'translate(' + (-secondLineOffset) + 'px, 0px)',
            opacity: '1'
        });
    }, 50);
}, 2000);

#ubercontainer {
    border: 1px solid #eaeaea;
    border-radius: 2px;
    background-color: #ffefc6;
    width: 500px;
    margin: 20px auto;
    padding: 30px 0;
}
#container {
    position: relative;
    text-align: center;
    font-family: sans-serif;
    font-size: 32px;
    font-weight: 800;
    color: #4a6b82;
    height: 78px;
}
.measurable {
    position: absolute;
    visibility: hidden;
}

.static.first, .static.second {
    transition: transform 1s ease;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ubercontainer">
<div id="container">
    <span class="the-first"></span> 
    <span class="static first">better websites </span><br />
    <span class="static second">made for</span> 
    <span class="the-second"></span>
</div>
</div>

这篇关于使用JavaScript平滑地更改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆