萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

8 個實用 jQuery 技巧:禁用右鍵、回頂端、圖片預載、滑鼠座標等

技巧 1:禁用右鍵選單 (含自訂右鍵選單擴充)

$(document).on('contextmenu', function(e) {
    // 簡單禁用
    // return false;
    
    // 進階:顯示自訂右鍵選單
    e.preventDefault();
    $('#custom-contextmenu')
        .css({ top: e.clientY, left: e.clientX, display: 'block' })
        .data('triggerTarget', e.target);
});

$(document).on('click', function() {
    $('#custom-contextmenu').hide();
});

技巧 2:動態調整頁面字體大小 (支援記憶偏好)

var FontSizer = {
    KEY: 'user-font-scale',
    DEFAULT: 1,
    MIN: 0.75,
    MAX: 2,
    STEP: 0.1,
    
    init: function() {
        this.scale = parseFloat(localStorage.getItem(this.KEY)) || this.DEFAULT;
        this.apply();
        $('#font-inc').click(() => this.adjust(this.STEP));
        $('#font-dec').click(() => this.adjust(-this.STEP));
        $('#font-reset').click(() => this.reset());
    },
    
    adjust: function(delta) {
        this.scale = Math.min(this.MAX, Math.max(this.MIN, this.scale + delta));
        this.apply();
        localStorage.setItem(this.KEY, this.scale);
    },
    
    reset: function() {
        this.scale = this.DEFAULT;
        this.apply();
        localStorage.removeItem(this.KEY);
    },
    
    apply: function() {
        $('html').css('font-size', (16 * this.scale) + 'px'); // 基準 16px
    }
};

$(FontSizer.init.bind(FontSizer));

技巧 3:外部連結自動新分頁開啟 (含 rel 安全屬性)

$(function() {
    $('a[href^="http"]').not('[href*="' + location.host + '"]').attr({
        target: '_blank',
        rel: 'noopener noreferrer' // 安全:防止反向存取 opener
    });
});

技巧 4:動態切換主題樣式表 (CSS 變數現代寫法)

// CSS
:root { --primary: #4490F7; --bg: #fff; --text: #333; }
[data-theme="dark"] { --primary: #559BFC; --bg: #1a1a1a; --text: #eee; }

// JS
$('#theme-toggle').click(function() {
    var isDark = $('html').toggleClass('dark').hasClass('dark');
    localStorage.setItem('theme', isDark ? 'dark' : 'light');
});

// 初始化
if (localStorage.getItem('theme') === 'dark') $('html').addClass('dark');

技巧 5:平滑捲動至頂部 / 指定元素

// 現代原生 (無需 jQuery)
function scrollToTop() {
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function scrollToElement(selector) {
    document.querySelector(selector)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// jQuery 版 (舊瀏覽器相容)
$('#back-to-top').click(function() {
    $('html, body').animate({ scrollTop: 0 }, 500, 'swing');
});

技巧 6:即時顯示滑鼠座標 (開發除錯用)

$('#debug-coords').remove(); // 避免重複
$('
') .appendTo('body'); $(document).on('mousemove', function(e) { $('#debug-coords').text(`X: ${e.pageX} | Y: ${e.pageY} | Client: ${e.clientX},${e.clientY}`); });

技巧 7:圖片預載入 (佇列控制、進度回呼、快取利用)

$.preloadImages = function(urls, options = {}) {
    var opts = $.extend({ concurrent: 3, onProgress: $.noop, onComplete: $.noop }, options);
    var loaded = 0, total = urls.length, running = 0, index = 0;
    
    function loadNext() {
        while (running < opts.concurrent && index < total) {
            var url = urls[index++];
            running++;
            $('').on('load error', function() {
                running--; loaded++;
                opts.onProgress(loaded, total, this.src, this.complete && this.naturalWidth > 0);
                loadNext();
            }).attr('src', url); // 瀏覽器自動快取
        }
        if (loaded === total) opts.onComplete();
    }
    loadNext();
};

// 使用
$.preloadImages([
    'img/banner1.jpg', 'img/banner2.jpg', 'img/banner3.jpg'
], {
    concurrent: 2,
    onProgress: (loaded, total, src, ok) => console.log(`[${loaded}/${total}] ${src} ${ok?'✓':'✗'}`),
    onComplete: () => console.log('所有圖片預載完成')
});

技巧 8:表單序列化為 JSON 物件 (含巢狀支援)

$.fn.serializeObject = function() {
    var obj = {};
    var arr = this.serializeArray();
    $.each(arr, function() {
        var name = this.name, value = this.value;
        // 支援 name="user[name]" 格式
        if (name.includes('[')) {
            var parts = name.split(/[\[\]]+/).filter(Boolean);
            var target = obj;
            for (var i = 0; i < parts.length - 1; i++) {
                target[parts[i]] = target[parts[i]] || {};
                target = target[parts[i]];
            }
            target[parts[parts.length - 1]] = value;
        } else {
            // 同名欄位自動轉陣列
            if (obj[name] !== undefined) {
                if (!Array.isArray(obj[name])) obj[name] = [obj[name]];
                obj[name].push(value);
            } else {
                obj[name] = value;
            }
        }
    });
    return obj;
};

// 使用
var formData = $('#myForm').serializeObject();
// { user: { name: 'Tom', age: '25' }, tags: ['js', 'jquery'], single: 'value' }

現代化替代方案提醒

  • 原生 fetch + FormData 取代 $.ajax。
  • CSS 變數 + class 切換 取代動態操作 style 屬性。
  • IntersectionObserver 取代 scroll 事件監聽懶載入。
  • 原生 element.closest()、matches() 取代 jQuery 遍歷。
copyright © 萬盛學電腦網 all rights reserved