记录学习与后端知识并分享学习代码过程(会飞的鱼Blog)

jQuery插件开发入门教程

会飞的鱼 0 2 2026年7月7日

jQuery插件开发入门教程

CSS Grid布局

.grid {
    display: grid;
    gap: 20px;
}

.grid-cols-3 {
    grid-template-columns: repeat(3, 1fr);
}

.grid-cols-4 {
    grid-template-columns: repeat(4, 1fr);
}

.grid-span-2 {
    grid-column: span 2;
}

.grid-row-span-2 {
    grid-row: span 2;
}

.grid-center {
    display: grid;
    place-items: center;
}

.grid-auto-fit {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

HTML5语义化标签

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语义化页面</title>
</head>
<body>
    <header>
        <nav>
            <h1>网站标题</h1>
            <ul>
                <li><a href="/">首页</a></li>
                <li><a href="/about">关于</a></li>
            </ul>
        </nav>
    </header>

    <main>
        <article>
            <h2>文章标题</h2>
            <p>文章内容...</p>
            <figure>
                <img src="image.jpg" alt="图片">
                <figcaption>图片说明</figcaption>
            </figure>
        </article>

        <aside>
            <h3>侧边栏</h3>
        </aside>
    </main>

    <footer>
        <p>&copy; 2024 版权所有</p>
    </footer>
</body>
</html>

CSS动画效果

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

.fade-in {
    animation: fadeIn 0.3s ease-out;
}

.slide-up {
    animation: slideUp 0.4s ease-out;
}

.spin {
    animation: spin 1s linear infinite;
}

.transition-all {
    transition: all 0.3s ease;
}

本地存储封装

class Storage {
    constructor(prefix = 'app_') {
        this.prefix = prefix;
    }

    set(key, value, expire = null) {
        const data = {
            value,
            expire: expire ? Date.now() + expire * 1000 : null
        };
        localStorage.setItem(this.prefix + key, JSON.stringify(data));
    }

    get(key) {
        const item = localStorage.getItem(this.prefix + key);
        if (!item) return null;

        try {
            const data = JSON.parse(item);
            if (data.expire && Date.now() > data.expire) {
                this.remove(key);
                return null;
            }
            return data.value;
        } catch {
            return null;
        }
    }

    remove(key) {
        localStorage.removeItem(this.prefix + key);
    }

    clear() {
        Object.keys(localStorage).forEach(key => {
            if (key.startsWith(this.prefix)) {
                localStorage.removeItem(key);
            }
        });
    }
}

响应式媒体查询

.container {
    width: 100%;
    padding: 15px;
    margin: 0 auto;
}

@media (min-width: 768px) {
    .container { width: 750px; }
    .col-md-6 { width: 50%; }
}

@media (min-width: 992px) {
    .container { width: 970px; }
    .col-lg-4 { width: 33.333%; }
    .desktop-nav { display: flex; }
    .mobile-menu { display: none; }
}

@media (min-width: 1200px) {
    .container { width: 1170px; }
}

@media (prefers-color-scheme: dark) {
    body { background: #1a1a1a; color: #fff; }
}

jQuery工具包

$(function() {
    $('#btn').click(function() { alert('点击了!'); });
    $('.btn').addClass('active');
    $('input[name="email"]').val('test@example.com');

    $('#title').text('新标题');
    $('#content').html('<strong>加粗文字</strong>');
    $('#box').addClass('highlight');
    $('#box').toggleClass('active');

    $('#box').css({
        'color': 'red',
        'font-size': '16px'
    });

    $(document).on('click', '.dynamic-btn', function() {
        console.log('动态按钮点击');
    });

    $.getJSON('/api/data', function(data) {
        console.log(data);
    });

    $('#box').fadeIn(300);
    $('#box').slideToggle(300);
});

Flexbox工具类

.flex { display: flex; }
.flex-column { flex-direction: column; }
.flex-wrap { flex-wrap: wrap; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.justify-around { justify-content: space-around; }
.items-center { align-items: center; }
.items-start { align-items: flex-start; }
.items-end { align-items: flex-end; }
.flex-1 { flex: 1; }
.flex-none { flex: none; }
.flex-shrink-0 { flex-shrink: 0; }

.flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
}

.flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

工具函数

const utils = {
    debounce(fn, delay = 300) {
        let timer = null;
        return function(...args) {
            clearTimeout(timer);
            timer = setTimeout(() => fn.apply(this, args), delay);
        };
    },

    throttle(fn, delay = 300) {
        let last = 0;
        return function(...args) {
            const now = Date.now();
            if (now - last >= delay) {
                last = now;
                fn.apply(this, args);
            }
        };
    },

    deepClone(obj) {
        return JSON.parse(JSON.stringify(obj));
    },

    formatDate(date, format = 'YYYY-MM-DD') {
        const d = new Date(date);
        return format
            .replace('YYYY', d.getFullYear())
            .replace('MM', String(d.getMonth() + 1).padStart(2, '0'))
            .replace('DD', String(d.getDate()).padStart(2, '0'));
    }
};

表单验证

class FormValidator {
    constructor(formId) {
        this.form = document.getElementById(formId);
        this.rules = {};
        this.errors = {};
    }

    addRule(field, rules) {
        this.rules[field] = rules;
    }

    validate() {
        this.errors = {};
        for (let field in this.rules) {
            const value = this.form[field].value;
            for (let rule of this.rules[field]) {
                if (!this.checkRule(value, rule)) {
                    this.errors[field] = rule.message;
                    break;
                }
            }
        }
        return Object.keys(this.errors).length === 0;
    }

    checkRule(value, rule) {
        switch (rule.type) {
            case 'required':
                return value.trim() !== '';
            case 'email':
                return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
            case 'minLength':
                return value.length >= rule.min;
            default:
                return true;
        }
    }
}

AJAX封装

class HttpClient {
    constructor(baseURL = '') {
        this.baseURL = baseURL;
    }

    async request(url, options = {}) {
        const response = await fetch(this.baseURL + url, {
            ...options,
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            }
        });
        return response.json();
    }

    get(url, params = {}) {
        const query = new URLSearchParams(params).toString();
        return this.request(url + (query ? '?' + query : ''));
    }

    post(url, data = {}) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }
}

防抖节流详细实现

// 防抖
function debounce(fn, wait = 300, immediate = false) {
    let timer = null;
    let result;

    const debounced = function(...args) {
        if (timer) clearTimeout(timer);

        if (immediate) {
            const callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait);
            if (callNow) result = fn.apply(this, args);
        } else {
            timer = setTimeout(() => {
                fn.apply(this, args);
            }, wait);
        }

        return result;
    };

    debounced.cancel = function() {
        clearTimeout(timer);
        timer = null;
    };

    return debounced;
}

// 节流
function throttle(fn, wait = 300) {
    let previous = 0;

    return function(...args) {
        const now = Date.now();
        if (now - previous >= wait) {
            previous = now;
            fn.apply(this, args);
        }
    };
}

图片懒加载

class LazyLoad {
    constructor() {
        this.images = document.querySelectorAll('img[data-src]');
        this.observer = null;
        this.init();
    }

    init() {
        if ('IntersectionObserver' in window) {
            this.observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        this.loadImage(entry.target);
                        this.observer.unobserve(entry.target);
                    }
                });
            });

            this.images.forEach(img => this.observer.observe(img));
        } else {
            this.images.forEach(img => this.loadImage(img));
        }
    }

    loadImage(img) {
        img.src = img.dataset.src;
        img.classList.add('loaded');
    }
}

技术分享,欢迎评论区交流讨论。

本文由 @会飞的鱼 于 2026-7-7 发布在 会飞的鱼Blog,如无特别说明,本博文章均为原创,转载请保留出处。

网友评论

    暂无评论

会飞的鱼 在线咨询

在线时间:9:00-22:00
周六、周日:14:00-22:00