search
HomeWeb Front-endH5 Tutorial随机字符变换效果的jQuery插件开发教程

在这篇快速的jQuery插件开发教程中,我们将创建一个jQuery插件用来随机排序显示任何一个DOM元素的文字内容 -这将会是一个非常有趣的效果,可以用在标题,logo及其幻灯效果中。

随机字符变换效果的jQuery插件开发教程

 

在线演示       在线下载

 

代码片段

那么第一部呢,我们将开发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, upperletter或者symbol),并且返回一个随机字符。

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)];
}

我们本应该使用一个简单的字符池来保存所有的字符,但是这样会有更好效果。

现在我们来书写插件的body部分:

$.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;ilen){
                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);
    });
};

这 个插件将可以接受被调用的DOM元素的内容,或者当作一个参数传入的对象的text属性。然后它分割字符串到字符,并且决定使用的类型。这个 shuffle功能使用setTimeout()来调用自己并且随机生成字符串,更新DOM元素。如果你不清楚setTimeout()的使用,可以参考 这篇文章:http://www.gbin1.com/technology/jqueryhowto/fadeoutonebyone/ , 调用seTimeout方法可以帮助你按特定时间间隔执行某些操作。

以上就是随机字符变换效果的jQuery插件开发教程的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),