jquery函数需要在页面加载时运行

时间:2015-03-11 03:29:10

标签: javascript jquery

我有这个功能,可以让文字在拼出实际单词之前循环显示一系列字母。目前,它在悬停时执行此操作 - 但我希望它只在页面加载时才能执行此操作。

(function($){

$.fn.charcycle = function( options ){
    var settings = {
        target:"",
        sender:$(this),
        id:$(this).attr('id'),
        timer_is_on:1,
        quoteDis : "",
        quoteLoc : 0,
        speed:90,
        quotePic :   "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
        quotePic2 :  "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
        quotePic3 :  "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
        quoteStr : "",
        targetElement :""
    }
//var quoteStr;
//var targetElement;
var quoteLen;
var quoteMax;
var rndRange;
var t;

return this.each(function(){

    if ( options ) { 
        $.extend( settings, options );
    }

    $(this).addClass('cycling');

    settings.targetElement=$(this).find(settings.target);
    settings.quoteStr=settings.targetElement.text();


    startQuote();

    function padQuote(){
        for (var i = settings.quoteStr.length; i < quoteMax; i++) {
            settings.quoteStr= "" + settings.quoteStr + " ";
        }
    }

function disQuote() {
    settings.quoteDis = settings.quoteStr.substring(0, settings.quoteLoc);

    for (var i = settings.quoteLoc; i < quoteMax; i++){

        var charone;
        charone = settings.quoteStr.substring(i, i + 1);

        var rdnum;
        rdnum = Math.floor(Math.random() * rndRange)

        if(i< quoteMax && i>quoteMax-3){
            settings.quoteDis = "" + settings.quoteDis + settings.quotePic3.substring(rdnum, rdnum + 1);
        }
        else if (i > settings.quoteLoc+7 && i < settings.quoteLoc+14){

            settings.quoteDis = "" + settings.quoteDis + settings.quotePic.substring(rdnum, rdnum + 1);
        } 
        else {

            settings.quoteDis = "" + settings.quoteDis + settings.quotePic2.substring(rdnum, rdnum + 1);
        }
    }
    settings.quoteLoc = settings.quoteLoc + 1;
    if(settings.quoteLoc == quoteLen+2){
         //$("#"+settings.id).removeClass('cycling');
         settings.sender.removeClass('cycling');
         clearTimeout(t);
         settings.timer_is_on=0;
    }
}

function loopQuote(target) {

    settings.targetElement.text(settings.quoteDis);
    disQuote();

    if (settings.timer_is_on==1){
        t = setTimeout(function(){loopQuote(target)}, settings.speed);
        settings.speed=settings.speed+0.75;
    }

    if(quoteMax < quoteLen){
        quoteMax = quoteMax+3;  
    }
}

function startQuote() {

    quoteMax = settings.quoteStr.length;
    rndRange=settings.quotePic.length;
    quoteLen = settings.quoteStr.length;

    padQuote();
    disQuote();
    loopQuote();

}

});
}

})( jQuery );

$('#banner').mouseenter(function(){
if($(this).hasClass('cycling')==false){ 
    $(this).charcycle({'target':'#text'});  
}
});

来自http://codepen.io/felipeBB/pen/XJaBMP

1 个答案:

答案 0 :(得分:0)

正如泰米尔人所说,把整件事放在$document.ready()并删除鼠标悬停:http://codepen.io/anon/pen/ByqjWY?editors=101