DIV CSS 佈局教程網

用不同的 jQuery API 處理各種瀏覽器事件
編輯:JQuery特效代碼     

在今天的瀏覽器中,事件處理一直是比較棘手的一塊,因為不同瀏覽器對事件的處理方式各異。要克服這些跨瀏覽器問題,就可以善用 jQuery 的事件處理 API。jQuery 是一個小巧的 JavaScript 函式庫,提供了大量處理事件、效果與更多功能的 API。本教學將介紹幾個用來處理瀏覽器事件的 jQuery API。

頁面載入事件 ready(fn)
這是所有事件的基礎。你可能想在頁面載入時設定表單焦點或做一些 UI 效果:

$(document).ready(function () {
    $("p").text("The DOM is now loaded and can be manipulated.");
});

事件處理 bind(type, data, fn)
可以為一個或多個元素綁定 click/dblclick 等事件處理器:

$("p").bind("click", function(e) {
    var str = "( " + e.pageX + ", " + e.pageY + " )";
    $("span").text("Click happened! " + str);
});
$("p").bind("dblclick", function() {
    $("span").text("Double-click happened in " + this.tagName);
});
$("p").bind("mouseenter mouseleave", function(e) {
    $(this).toggleClass("over");
});

觸發事件 trigger(type, data)
在每個符合的元素上觸發事件,也會觸發瀏覽器同名的預設行為(例如觸發 submit 會送出表單)。觸發的事件不限於瀏覽器內建事件,也能觸發自訂事件:

$("button:first").click(function () {
    update($("span:first"));
});
$("button:last").click(function () {
    $("button:first").trigger('click');
    update($("span:last"));
});
function update(j) {
    var n = parseInt(j.text(), 10);
    j.text(n + 1);
}

互動輔助 hover(over, out)
提供懸停功能:滑鼠移入符合元素時觸發第一個函式,移出時觸發第二個。它能避免滑鼠移到元素內部子元素時誤觸 mouseout 的常見錯誤:

$("li").hover(
    function () { $(this).append($("<span> ***</span>")); },
    function () { $(this).find("span:last").remove(); }
);

其他事件輔助方法:

blur()/blur(fn):觸發或綁定 blur 事件。

$("input").blur(function () {
    $(this).next("span").css('display','inline').fadeOut(1000);
});

change(fn):綁定 change 事件。

$("select").change(function () {
    var str = "";
    $("select option:selected").each(function () {
        str += $(this).text() + " ";
    });
    $("div").text(str);
}).change();

click(fn)/dblclick(fn):綁定點擊或雙擊事件。

$("p").click(function () { $(this).slideUp(); });
var divdbl = $("div:first");
divdbl.dblclick(function () { divdbl.toggleClass('dbl'); });

keypress(fn):綁定按鍵事件。

$("input").keypress(function (e) {
    if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
    || (97 <= e.which && e.which <= 97 + 25)) {
        var c = String.fromCharCode(e.which);
        $("p").append($("<span/>"))
        .children(":last")
        .append(document.createTextNode(c));
    } else if (e.which == 8) {
        $("p").children(":last").remove(); // IE 的 backspace 只在 keydown 觸發
    }
    $("div").text(e.which);
});

mousedown(fn)/mouseup(fn):綁定滑鼠按下與放開事件。

$("p").mouseup(function(){
    $(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
    $(this).append('<span style="color:#00F;">Mouse down.</span>');
});

scroll(fn):綁定滾動事件。

$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$(window).scroll(function () {
    $("span").css("display", "inline").fadeOut("slow");
});

透過這些 API,就能用一致的寫法處理跨瀏覽器的事件,大幅降低相容性上的困擾。

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