JavaScript >> Javascript 文檔 >  >> jQuery

隨機字母效果:一個 jQuery 插件

在這個簡短的教程中,我們將製作一個 jQuery 插件,它將隨機播放任何 DOM 元素的文本內容 - 一種可用於標題、徽標和幻燈片的有趣效果。

代碼

第一步是編寫我們的 jQuery 插件的主幹。我們將代碼放在一個自動執行的匿名函數中,並擴展 $.fn .

assets/js/jquery.shuffleLetters.js

(function($){

    $.fn.shuffleLetters = function(prop){

        // Handling default arguments
        var options = $.extend({
            // Default arguments
        },prop)

        return this.each(function(){
            // The main plugin code goes here
        });
    };

    // A helper function

    function randomChar(type){
        // Generate and return a random character
    }

})(jQuery);

接下來我們將注意力轉向randomChar() 輔助功能。它將接受一個類型參數(“lowerLetter ", "大寫字母 " 或 "符號 ") 並返回一個隨機字符。

function randomChar(type){
    var pool = "";

    if (type == "lowerLetter"){
        pool = "abcdefghijklmnopqrstuvwxyz0123456789";
    }
    else if (type == "upperLetter"){
        pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    else if (type == "symbol"){
        pool = ",.?/\\(^)![]{}*&^%$#'\"";
    }

    var arr = pool.split('');
    return arr[Math.floor(Math.random()*arr.length)];
}

我們本可以對所有類型的字符使用單個池字符串,但這樣做效果會更好。

現在讓我們編寫插件的主體!

$.fn.shuffleLetters = function(prop){

    var options = $.extend({
        "step"  : 8,    // How many times should the letters be changed
        "fps"   : 25,   // Frames Per Second
        "text"  : ""    // Use this text instead of the contents
    },prop)

    return this.each(function(){

        var el = $(this),
            str = "";

        if(options.text) {
            str = options.text.split('');
        }
        else {
            str = el.text().split('');
        }

        // The types array holds the type for each character;
        // Letters holds the positions of non-space characters;

        var types = [],
            letters = [];

        // Looping through all the chars of the string

        for(var i=0;i<str.length;i++){

            var ch = str[i];

            if(ch == " "){
                types[i] = "space";
                continue;
            }
            else if(/[a-z]/.test(ch)){
                types[i] = "lowerLetter";
            }
            else if(/[A-Z]/.test(ch)){
                types[i] = "upperLetter";
            }
            else {
                types[i] = "symbol";
            }

            letters.push(i);
        }

        el.html("");            

        // Self executing named function expression:

        (function shuffle(start){

            // This code is run options.fps times per second
            // and updates the contents of the page element

            var i,
                len = letters.length,
                strCopy = str.slice(0); // Fresh copy of the string

            if(start>len){
                return;
            }

            // All the work gets done here
            for(i=Math.max(start,0); i < len; i++){

                // The start argument and options.step limit
                // the characters we will be working on at once

                if( i < start+options.step){
                    // Generate a random character at this position
                    strCopy[letters[i]] = randomChar(types[letters[i]]);
                }
                else {
                    strCopy[letters[i]] = "";
                }
            }

            el.text(strCopy.join(""));

            setTimeout(function(){

                shuffle(start+1);

            },1000/options.fps);

        })(-options.step);

    });
};

該插件將採用 contents 它被調用的 DOM 元素的名稱,或 text 作為參數傳遞的對象的屬性。然後它將字符串拆分為字符並確定每個字符的類型。然後 shuffle 函數使用 setTimeout() 調用自身並隨機化字符串,在每一步更新 DOM 元素。

當您前往演示時,您會看到您可以輸入自己的文本並進行測試。我是這樣做的:

assets/js/script.js

$(function(){

    // container is the DOM element;
    // userText is the textbox

    var container = $("#container")
        userText = $('#userText'); 

    // Shuffle the contents of container
    container.shuffleLetters();

    // Bind events
    userText.click(function () {

      userText.val("");

    }).bind('keypress',function(e){

        if(e.keyCode == 13){

            // The return key was pressed

            container.shuffleLetters({
                "text": userText.val()
            });

            userText.val("");
        }

    }).hide();

    // Leave a 4 second pause

    setTimeout(function(){

        // Shuffle the container with custom text
        container.shuffleLetters({
            "text": "Test it for yourself!"
        });

        userText.val("type anything and hit return..").fadeIn();

    },4000);

});

上面的片段還展示瞭如何使用插件和自定義 text 參數。

完成

我希望你發現這個插件有用並且玩得開心。它是在 MIT 許可下發布的。


Tutorial JavaScript 教程
  1. 賽普拉斯 - UI 測試自動化 - 訪問元素介紹

  2. 代碼和 Scrum 100 天的第 92 天:使用 next-auth 保護 Next.js 應用程序

  3. 前端結束和後端開始的地方

  4. 使用 grandjs 在 nodejs 中構建嵌套路由

  5. jquery創建二維數組

  6. 使用 ViewEncapsulation 在 Angular 2 中模擬或原生 Shadow DOM

  7. JavaScript / 谷歌地圖中的磁偏角

  1. 跟我一起學習 D3.js:選擇元素並將其附加到 DOM(帖子 #1)。

  2. 區分 +0 和 -0

  3. NextJS 中的 GraphQL 查詢與 useSWR 和 graphql-request

  4. 有趣的打印機黑客

  5. 使用 React Lazy 和 React Suspense 拆分 React Router 路由的代碼

  6. Vue.js 類型化事件

  7. 它是最好的角度還是反應

  1. 你已經使用了類型——這就是為什麼你應該使用類型系統

  2. 如何輕鬆調試 rxjs 管道

  3. 在ionic 4中實現投票功能。

  4. Axios 還是 Fetch?- 在 2 分鐘內