how to preventDefault inside switch e.which

问题: 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();
        });
  • 发表于 2019-01-04 18:11
  • 阅读 ( 202 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除