mouse events - contextmenu and selectstart

Disable right mouse button menu - contextmenu

contextmenu mainly controls when the context menu should be displayed, mainly for programmers to cancel the default context menu

Example image of the right-click menu:

insert image description here

The main code of contextmenu:

// 1. contextmenu 禁用右键菜单
    document.addEventListener('contextmenu', function(e){
    
    
      e.preventDefault()
    })

Here I choose to directly use the document node document to disable the right-click menu on the entire page
, but you can still use ctrl + c to achieve the purpose of copying text.

Disable selection - selectstart

select selection; start start; the trigger time is when the target object is initially selected (that is, the selection action has just started and has not been substantially selected). This event is often used to make the target object "forbidden to turn blue". For example, when the user double-clicks in many places, some elements will turn blue (selected state), and we can use this event when we want to avoid this situation.
The effect diagram before the default behavior is not blocked:
insert image description here
it can be seen in the figure that when we select any part of the document, the selection event is triggered immediately. Prompt that the selection here is not just the text but the entire document.

Sample code:

document.addEventListener('selectstart', function(){
    
    
      console.log('我被选中啦');
    })

To disable the selected event is to add to prevent the default behavior

Sample code:

// 2. selectstart 禁止选中文字  
    document.addEventListener('selectstart', function(e){
    
    
      e.preventDefault()
    })

Guess you like

Origin blog.csdn.net/weixin_46278178/article/details/126991661