簡體   English   中英

如何僅在單擊背景(而不是其他元素)時觸發 Javascript 事件?

[英]How to get Javascript event to fire only when the background is clicked (and not other elements)?

我正在嘗試編寫一個 Web 應用程序,用我自己的自定義菜單替換上下文菜單(右鍵單擊菜單)。 我想要這樣,當用戶點擊表格行時,他們會得到一個特定的上下文菜單,而當他們點擊頁面的背景時,他們會得到一個不同的上下文菜單。

我已經編寫了菜單並讓它們工作。 當試圖弄清楚如何使背景菜單僅在單擊背景時顯示以及如何在單擊時顯示表格行菜單時出現問題。

我嘗試對正文使用document.body.oncontextmenu並為每個表格行設置oncontextmenu函數,但是正文的oncontextmenu函數覆蓋了該行的函數,所以我得到了錯誤的菜單。 如果我停止使用正文的菜單,表格行的菜單就可以工作,所以這不是問題。

我可能使用了錯誤的事件,那么是否有不同的事件僅用於背景(而不是背景頂部的元素)? 或者一種“優先”事件的方法,以便表行的功能優先?

這是代碼的樣子:

var tableMenu;
var bodyMenu;

window.onload = function()
{
    bodyMenu = new rightClickMenu("bodyMenu");
    document.body.oncontextmenu = function() { bodyMenu.show(); tableMenu.hide(); }
    bodyMenu.add("Add Entry", function()
    {
        alert("ADD");
    });
    
    tableMenu = new rightClickMenu("tableMenu", "tblSims");

    simRows = getElementsByClassName("trSimRow");
    for (var i in simRows)
        simRows[i].oncontextmenu = function() { tableMenu.show(this.id.substring(2)); bodyMenu.hide(); }

    tableMenu.add("Delete Entry", function(mac)
    {
        alert("DELETE");
    });
    
    document.body.onclick = function()
    {
        bodyMenu.hide();
        tableMenu.hide();
    };
}

您可以捕獲目標元素,例如:

$('*').click(function(e) {
    alert(e.target);
    alert(e.target.tagName);
    if(e.target.tagName == 'html') {
        // show background menu
    }
});

您必須使用 Javascript 事件傳播模型。 發生的情況是您的點擊事件會自動向下傳遞到頁面上已注冊為事件偵聽器的對象層,除非您明確告訴它停止,請嘗試以下操作:

function setupClickHandlers()
{
    document.getElementsByTagName('body')[0].onclick = doBodyMenu;
    document.getElementById('tableID').onclick = doTableMenu;
}

function doBodyMenu()
{
    //do whatever it does
}

function doTableMenu(e)
{
    //do whatever it does

    //stop the event propagating to the body element
    var evt = e ? e : window.event;

    if (evt.stopPropagation) {evt.stopPropagation();}
    else {evt.cancelBubble=true;}
    return false;
}

這應該處理每個瀏覽器處理事件的方式。

 $( document ).ready(function() { var childClicked = false; // myContainer is the nearest container div to the clickable elements $("#myContainer").children().click(function(e) { console.log('in element'); childClicked = true; }); $("#myContainer").click(function(e){ if(!childClicked) { console.log('in background'); e.preventDefault(); e.stopPropagation(); } childClicked = false; }); });
 #myContainer { width:200px; height:200px; background-color: red; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myContainer" style=""> <a href="#">link</a> <div style="width:50px;height:50px;background-color: white;"> <a href="#">another link</a> </div> </div>

暫無
暫無

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

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