0

これは私のコードの簡略化された説明バージョンです:

    var ptext=parr.find('div.ptext');   //Text Container

    var pt=ptext.html();                //Text Container's string
    var pdv=[pt.split(" ")];            //Text Container's array of words
        pdv.push(pdv[0].length);    //Write also the number of words

    var ht=hp.html();               //Text Container's new string
    var hdv=[ht.split(" ")];            //Text Container's new array of words
    hdv.push(hdv[0].length);            //New number of words

    var kakaka=0;                       //If they begin with the same,
    for (var j=0;j<hdv[0].length;j++){  //Animate only from the position
        if (hdv[0][j]==pdv[0][j])   //where they differ
            kakaka+=2;
    }

    window.clearTimeout(ptext.data('curt'));  //Clear current animation's interval
    ptext.data('count',kakaka);      //Set starting position    
    ptext.data('curt',                      //Set interval's var into object
        window.setInterval((function (item,pdv,hdv,text_callback) {
                return function() {       //item = text obj, text_callback= callback function
                        var i=item.data('count');
                            i=(i==undefined)?0:1+i;
                        item.data('count',i);     //increase counter
                                //first phase - remove old text
                        if (i<=pdv[1])       // go on
                        {
                            item.html((pdv[0].slice(0,pdv[1]-i)).join(' '));
                        }       //if reached the position, add new text
                        else if (i<=pdv[1]+hdv[1])
                        {
                            item.html((hdv[0].slice(0,i-pdv[1])).join(' '));
                        }        //if finish clear timeout and call callback
                        else {
                            item.data('count',0);
                            window.clearTimeout(item.data('curt'));
                            text_callback();
                        }
                }
            })(ptext,pdv,hdv,text_callback),8)   //8 = supposed interval
       );


}

divから単語を取得し、それらを1つずつすばやく削除してから、新しいテキストを入力します。

これは、8msごとにコールバックすることになっている.setInterval()関数を使用します。これは私のi5CPUでうまく機能しますが、i3ラップトップではひどく遅いです。

パフォーマンスを向上させる方法についてアドバイスをいただけますか?

4

3 に答える 3

1

あなたは出来る

  • ドキュメントの再描画とリフローを回避するために、コンテナの幅と高さを設定してみてください。操作後に要素のサイズを変更します。
  • そうすれば、配列操作(分割と結合)を回避し、文字列操作を直接使用できます。
  • ループ操作の外部に参照を格納することにより、同じ要素への繰り返しの呼び出しを回避します
  • text()の代わりに使用するとhtml()、DOMはテキストノードのみを作成します。

これがデモで、信頼できるPentium4で非常に高速に実行されます

$(function() {

    function clearText(selector, callback) {
        //cache repeatedly used items
        var element = $(selector),
            elementText = element.text() + ' '; 

        //set element dimensions to fixed
        element.width(element.width());    
        element.height(element.height());

        (function erase() {
            if (elementText) {
                //use slice operations instead
                elementText = elementText.slice(elementText.indexOf(' ')+1);
                //use "text()"
                element.text(elementText);
                //loop
                setTimeout(function() {
                    erase();
                }, 8);
            } else {
                //set the dimensions back to auto
                element.width('auto').height('auto');   
                //execute callback returning the jQuery element
                callback.apply(element); 
            }
        }())

    }

    clearText('#foo', function() {
        //"this" is jQuery object "#foo"
        this.text('hello world');
    });
});​
于 2012-05-18T03:32:40.243 に答える
1

これでうまくいきます。setTimeout呼び出し間のラグを変更することをお勧めします。それはもっと自己完結型にすることができますが、私には今のところ動機がありません:

<script type="text/javascript">

// Some support functions
(function(g) {
  var el = document.createElement('div');
  if (typeof el.textContent == 'string') {
    g.getText = function(el) {return el.textContent};
    g.setText = function(el, text) {el.textContent = text};
  }

  if (typeof el.innerText == 'string') {
    g.getText = function(el) {return el.innerText};
    g.setText = function(el, text) {el.innerText = text};
  }
}(this));

function annoyUser(el, text) {
  var re = /\s+/g;
  var oText = getText(el).split(re);

  if (oText.length == 1) {
    setText(el, text);

  } else {
    oText.pop();
    setText(el, oText.join(' '));
    setTimeout(function(){annoyUser(el, text)}, 100);
  }
}

window.onload = function() {
  setTimeout(function() {
    annoyUser(document.getElementById('d0'), 'hello world')
  }, 1000);
}

</script>

<div id="d0">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas
 metus sapien, lobortis non dictum et, mollis vitae lorem. Nulla facilisi. Morbi eget
 ante diam.</div>
于 2012-05-18T03:39:08.097 に答える
-1

これは完璧に機能しました。全体のアイデアは、スパンでラップすることでした。次に、スパンごとに可視性を変更し、逆のフェーズになったら、スパンでラップされた別のテキストに置き換えます。

私はあなたが何かを理解することを保証するものではありませんが、私がそれをどのように解決したかは確かに理解できます。基本的に、主な入力はpdvであり、hdv-は入力テキストと出力テキストの単語配列であることに注意してください。

function letsdance(obj,op,type,text_callback){  //animate text

    if (text_callback==undefined) var text_callback=function(){};

    var parr=obj.parents('.pconter');
    var ptext=parr.find('div.ptext');


    var pt=ptext.html();

    var ppp=ptext.children();
    var pdv=[[]];
    for (var i=0;i<ppp.length;i++)
        pdv[0].push(    ppp[i].outerHTML    );



    if (ppp.length==0){
    var pdv=[pt.split(" ")];
        for (var i=0;i<pdv[0].length;i++)
            pdv[0][i]='<span>'+pdv[0][i]+'</span>';
        ptext.html(pdv[0].join(' '));
    }

    pdv.push(pdv[0].length-1);

    if (op){
        if (type===1)
            {
                var ht=obj.html();
            }
        else if (type==2)
            {
                var ht=ptext.data('orig');  
            }
        else {
        var ide=(obj.attr('id').match(/_[\da-zA-Z]*_[\da-zA-Z]*$/))[0];
        var hp=parr.find('div.hptext[id$="'+ide+'"]');
        var ht=hp.html();   
        }
        var hdv=[ht.split(" ")];
            hdv.push(hdv[0].length-1);  
    } else {    
        var current_selection=parseInt(ptext.data('current_section'));
        if (current_selection>0){
            var pto=ptext.siblings('.subptext[id$="NN'+current_selection+'"]').html();
            }
        else 
            var pto=ptext.data('orig');

        var hdv=[pto.split(" ")];
            hdv.push(hdv[0].length-1);  
    }

    var kakaka=0;
    var kaka=false;
    for (var i=0;i<=hdv[1];i++){
        if (pdv[0][i]!=undefined&&!kaka&&hdv[0][i]==pdv[0][i].replace(/(<([^>]+)>)/ig,"")&&!/invis/.test(pdv[0][i])){
                        kakaka+=1;  
        }
        else {
            kaka=true;
            hdv[0][i]='<span class="invis">'+hdv[0][i]+'</span>'; 
        }
    }
    var invi_count=pdv[1];
    for (invi_count;invi_count>=0;invi_count--)
        if (!/invis/.test(pdv[0][invi_count])) break;

    window.clearInterval(ptext.data('curt'));
    ptext.data('count',invi_count).data('index',kakaka).data('phase',0)//data('skip',0);            
    ptext.data('curt',
        window.setInterval((function (item,pdv,hdv,text_callback) {
                return function() {
                    var i=item.data('count');      
                    var phase=item.data('phase');      
                    var index=item.data('index');    
                    switch (phase)
                    {
                        case 0:
                                item.children(':eq('+i+')').addClass('invis');
                                if (i>index)    
                                    item.data('count',i-1);
                                else
                                    item.data('count',index).data('phase',1)
                                    .html((pdv[0].slice(0,index)).join(' ')).append(' '+hdv[0].slice(index,hdv[1]).join(' '));
                        break;  
                        case 1:
                                item.children(':eq('+i+')').removeClass('invis');
                                if (i<hdv[1])
                                    item.data('count',i+1);
                                else{
                                    //item.data('count',0).data('phase',0);
                                    window.clearInterval(item.data('curt'));
                                    text_callback();
                                }
                        break;      
                    }
                }
            })(ptext,pdv,hdv,text_callback),4)
       );


}
于 2012-06-15T02:11:06.590 に答える