Jquery/JS prevent right click menu in browsers

前端 未结 12 1724
孤城傲影
孤城傲影 2020-12-03 00:42

I have my div with a right click popup menu:

// Attatch right click event to folder for extra options
$(\'#fBox\' + folderID).mousedown(function(event) {
            


        
12条回答
  •  北海茫月
    2020-12-03 01:12

    I agree with @aruseni, blocking oncontextmenu at the body level you'll avoid the standard context menu on the right click for every element in the page.

    But what if you want to have a finer control?

    I had a similar issue and I thought I've found a good solution: why not attaching directly your context menu code to the contextmenu event of the specific element(s) you want to deal with? Something like this:

    // Attatch right click event to folder for extra options
    $('#fBox' + folderID).on("contextmenu", function(event) {
      // <-- here you handle your custom context menu
      // Set ID
      currRClickFolder = folderID;
    
      // Calculate position to show popup menu
      var height = $('#folderRClickMenu').height();
      var width = $('#folderRClickMenu').width();
      leftVal = event.pageX - (width / 2) + "px";
      topVal = event.pageY - (height) + "px";
      $('#folderRClickMenu').css({ left: leftVal, top: topVal }).show();
    
      event.stopImmediatePropagation();
      return false; // <-- here you avoid the default context menu
    });
    

    Thus you avoid handling two different events just to capture the context menu and customize it :)

    Of course this assumes you don't mind having the standard context menu displayed when someone clicks the elements you didn't select. You might as well show different context menus depending on where users right-click..

    HTH

提交回复
热议问题