DIV CSS 佈局教程網

8 個實用的 jQuery 小技巧,直接複製就能用
編輯:JQuery特效代碼     

1. 停用右鍵選單

想保護頁面上的資訊不被隨手另存時,攔截 contextmenu 是最直接的做法。

$(document).ready(function() {
    $(document).bind("contextmenu", function(e) {
        alert("No right-clicking!");
        return false;   // 取消預設的右鍵選單
    });
});

2. 讓使用者自行調整文字大小

$(document).ready(function() {
    var originalFontSize = $('html').css('font-size');

    $(".increaseFont").click(function() {
        var current = parseFloat($('html').css('font-size'), 10);
        $('html').css('font-size', current * 1.2);
        return false;
    });

    $(".decreaseFont").click(function() {
        var current = parseFloat($('html').css('font-size'), 10);
        $('html').css('font-size', current * 0.8);
        return false;
    });

    $(".resetFont").click(function(){
        $('html').css('font-size', originalFontSize);
    });
});

把基準設在 html 元素上,頁面中所有用 em 或百分比定義的字級都會跟著縮放,這對需要兼顧視力友善的站點很實用。

3. 外部連結自動在新視窗開啟

$(document).ready(function() {
    $("a[href^='http']").attr('target', '_blank');
});

4. 動態切換樣式表

$(document).ready(function() {
    $("a.cssSwap").click(function() {
        // 把 link 的 rel 值當成新的 href 塞進去
        $('link[rel=stylesheet]').attr('href', $(this).attr('rel'));
    });
});

5. 回到頁面頂端

長頁面閱讀到尾端時特別有用。

$(document).ready(function() {
    $('#top').click(function() {
        $(document).scrollTo(0, 500);
    });
});

6. 取得滑鼠游標的 X / Y 座標

$().mousemove(function(e){
    $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});

7. 即時監看游標位置

與上一個技巧概念相同,只是把輸出目標換成特定元素,方便除錯時觀察。

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

8. 圖片預先載入

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…');
});

預載入的原理是在記憶體中建立 Image 物件讓瀏覽器提前抓圖,等使用者真正把游標移到 hover 切換的區塊時,畫面就不會有等待的二段閃現。這對投影片式輪播或滑鼠移入換圖的介面效果明顯。

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