-2

jquery 函数“.textAnim”什么都不做 textTyping_animation(); 工作正常,但 .textAnim 不起作用。这是插件代码:

function textTyping_animation(text,location,speed){
var progress = 0;
var a = setInterval(function(){
    progress++;
    document.getElementById(location).innerHTML = text.substring(0,progress);
    if(progress == text.length){
        clearInterval(a);
    }
},speed);
};
(function($){
$.fn.textAnim = function(text,speed){
    var progress = 0;
    var a = setInterval(function(){
        progress++;
        $(this).html(text.substring(0,progress));
        if(progress == text.length){
            clearInterval(a);
        }
    },speed);
};
})(jQuery);

这是执行:

$(document).ready(function(){
starttext = function()
{
    document.getElementById("textbox").style.display = "block";
    //textTyping_animation("Dit is een dummy text!","textbox_inner",70);
        $("#textbox_inner").textAnim("Dit is een dummy text!",70);
}
});

html加载代码:

<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<script type="text/javascript" language="javascript" src="js/jqueryplugins.js" ></script>
<script type="text/javascript" language="javascript" src="js/libraries/gamelibrary.js"></script>
4

2 回答 2

1

问题是this传递给的回调函数内部setInterval()是窗口,而不是您想要的元素。修改您的代码以保存对函数this内部的引用textAnim()(它确实引用了正确的元素),然后在传递给的回调中使用它setInterval()

(function($){
    $.fn.textAnim = function(text,speed){
        var progress = 0,
            element = this; // this will be the element in the jQuery object
        var a = setInterval(function(){
            progress++;
            $(element).html(text.substring(0,progress));
            if(progress == text.length){
                clearInterval(a);
            }
        },speed);
    };
})(jQuery);

这是一个更新的演示

于 2012-11-27T15:44:20.350 回答
0

改变

$(document).ready(function(){
starttext = function()
{
    document.getElementById("textbox").style.display = "block";
    //textTyping_animation("Dit is een dummy text!","textbox_inner",70);
        $("#textbox_inner").textAnim("Dit is een dummy text!",70);
}
});

成为

$(document).ready(function(){
starttext = function()
{
    document.getElementById("textbox").style.display = "block";
    //textTyping_animation("Dit is een dummy text!","textbox_inner",70);
        $("#textbox_inner").textAnim("Dit is een dummy text!",70);
}
starttext();
});

它应该可以工作;

于 2012-11-27T15:24:34.430 回答