DIV CSS 佈局教程網

前端工程師常用的 jQuery 實用小貼士與技巧
編輯:JQuery特效代碼     

jQuery 雖然已不再是新項目的唯一選擇,但在大量存量項目中依然扮演著重要角色。本文精選了八個前端工程師日常開發中非常實用的 jQuery 小技巧,幫助你提升開發效率。

1. 禁用鼠標右鍵點擊

通過捕獲 contextmenu 事件並返回 false,即可禁用網頁上的右鍵菜單:

$(document).ready(function () {
    // 捕獲右鍵菜單
    $(document).bind("contextmenu", function (e) {
        // 可選的警告提示
        alert("No right-clicking!");
        // 取消默認的上下文菜單
        return false;
    });
});

2. 動態調整文字大小

利用 jQuery 讀取並修改 html 元素的 font-size,即可實現文字的放大、縮小與重置:

$(document).ready(function () {
    // 找到當前字體大小
    var originalFontSize = $('html').css('font-size');

    // 增大文字
    $(".increaseFont").click(function () {
        var currentFontSize = $('html').css('font-size');
        var currentFontSizeNumber = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNumber * 1.2;
        $('html').css('font-size', newFontSize);
        return false;
    });

    // 減小文字
    $(".decreaseFont").click(function () {
        var currentFontSize = $('html').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum * 0.8;
        $('html').css('font-size', newFontSize);
        return false;
    });

    // 重置字體大小
    $(".resetFont").click(function () {
        $('html').css('font-size', originalFontSize);
    });
});

3. 讓鏈接在新窗口打開

為所有以 http 開頭的鏈接自動添加 target="_blank",讓點擊後在新窗口打開:

$(document).ready(function () {
    // 選中所有 href 以 http 開頭的錨點,並設置 target=_blank
    $("a[href^='http']").attr('target', '_blank');
});

4. 樣式表切換

通過修改 link 標簽的 href,可以實現樣式表的動態切換:

$(document).ready(function () {
    $("a.cssSwap").click(function () {
        // 將 link 的 href 替換為點擊元素的 rel 值
        $('link[rel=stylesheet]').attr('href', $(this).attr('rel'));
    });
});

5. 回到頂部鏈接

對於內容較長的頁面,「回到頂部」功能十分實用,一鍵即可快速滾動到頁面頂端:

$(document).ready(function () {
    // 點擊 id="top" 的鏈接時
    $('#top').click(function () {
        // 將頁面滾動回頂部
        $(document).scrollTo(0, 500);
    });
});

6. 獲取鼠標光標的 x 和 y 坐標

通過 mousemove 事件可以實時獲取鼠標指針的坐標:

$().mousemove(function (e) {
    // 在 p 元素中顯示 x、y 軸數值
    $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});

7. 檢測當前鼠標坐標

同樣基於 mousemove 事件,可將當前鼠標坐標顯示到指定元素中:

$(document).ready(function () {
    $().mousemove(function (e) {
        $('#MouseCoordinates').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
    });
});

8. 在 jQuery 中預加載圖片

預加載圖片有助於讓圖像快速呈現,無需等待加載完成:

jQuery.preloadImagesInWebPage = function () {
    for (var ctr = 0; ctr < arguments.length; ctr++) {
        jQuery("<img>").attr("src", arguments[ctr]);
    }
};

// 使用方式
$.preloadImages("image1.gif", "image2.gif", "image3.gif");

// 檢查圖片是否加載完成
$('#imageObject').attr('src', 'image1.gif').load(function () {
    alert('The image has been loaded…');
});

以上八個技巧覆蓋了事件處理、樣式操作、坐標獲取、圖片預加載等常見場景,靈活運用能讓日常開發事半功倍。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved