簡體   English   中英

處理元素外部的點擊而不使用jquery

[英]Handling clicks outside an element without jquery

我想實現這樣的解決方案

如何檢測元素外部的單擊?

但我正在使用另一個已定義$()函數的javascript庫

有什么建議么?

這很容易實現。 為一個功能加載jQuery庫會很遺憾。

如果您正在使用的其他庫處理事件綁定,您可以在該庫中執行相同的操作。 由於您沒有指出其他庫是什么,這是一個原生解決方案:

示例: http //jsfiddle.net/patrick_dw/wWkJR/1/

window.onload = function() {

    // For clicks inside the element
    document.getElementById('myElement').onclick = function(e) {
            // Make sure the event doesn't bubble from your element
        if (e) { e.stopPropagation(); } 
        else { window.event.cancelBubble = true; }
            // Place the code for this element here
        alert('this was a click inside');
    };

    // For clicks elsewhere on the page
    document.onclick = function() {
        alert('this was a click outside');
    };
};

如果$沖突是你唯一的阻礙,那么可以解決這個問題: http//docs.jquery.com/Using_jQuery_with_Other_Libraries

我還在這里添加了阻止事件冒泡的代碼。 quircksmode.org找到

 function doSomething(e) {
    if (!e) var e = window.event
    // handle event
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
 } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM