簡單實現一個打字機效果

/**
 * 打字機效果功能
 * @param opts
 * 入參1: element;
 * 入參2: str;
 * 入參3: speed;
 * 入參4: callback;
 */
let index = function (opts) {
    let arr = [];
    for (let i = 0; i < opts.str.length; i++) {
        arr.push(opts.str[i]);
    }
    let text1 = '';
    let num = 0;
    let timer = setInterval(function () {
        if (num < arr.length) {
            text1 += arr[num];
            if (opts.element instanceof jQuery) {
                opts.element.html(text1);
            } else {
                opts.element.innerHTML = text1;
            }
            num++;
        } else {
            clearInterval(timer);
            opts.callback();
        }
    }, opts.speed);
};

module.exports = index;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章