问题:
Why preventDefault() on case 3 doesn't work? Browser's menu should not appear on right click.
$('#btnB').on('mousedown', function(e){
switch (e.which) {
ca...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
Why preventDefault()
on case 3
doesn't work? Browser's menu should not appear on right click.
$('#btnB').on('mousedown', function(e){
switch (e.which) {
case 1:
console.log('left');
break;
case 3:
e.preventDefault();
console.log('right');
break;
default:
alert('323');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='btnB'>CLICK</button>
回答1:
Same as answer of @dfsq, but with catch of double trigger on contextmenu. I cannot edit his answer for some reason and I want to show a demo.
$('#btnB').on('contextmenu mousedown', function(e) {
switch (e.which) {
case 1:
console.log('left');
break;
case 3:
if (e.type !== 'contextmenu') break;
e.preventDefault();
console.log('right');
break;
default:
alert('323');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="btnB">HAHAHA</span>
回答2:
Context menu appears because it reacts to different event, not mousedown. Try to listen both mousedown
(probably not needed even) and contextmenu
events:
$('#btnB').on('mousedown contextmenu', function(e){
switch (e.which) {
case 1:
console.log('left');
break;
case 3:
e.preventDefault();
console.log('right');
break;
default:
alert('323');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='btnB'>CLICK</button>
回答3:
If you want to prevent the context menu from opening you can do so by listening to the contextmenu event
$('#btnB').on('contextmenu', function(e) {
alert("hey new menu");
e.preventDefault();
});