jQuery: Detect Mouse Click and Open Target in New Tab

前端 未结 6 1900
暗喜
暗喜 2020-12-09 18:45

I\'m currently designing a simple forum application. It\'s mostly powered by jQuery/AJAX and loads everything on the same page; however, I know that sometimes users want to

相关标签:
6条回答
  • 2020-12-09 19:23
    <a href="some url" target="_newtab">content of the anchor</a>
    

    In javascript you can use

    $('#element').mousedown(function(event) {
          if(event.which == 3) { // right click
              window.open('page.html','_newtab');
          }
    })
    
    0 讨论(0)
  • 2020-12-09 19:26
        $('#element').mousedown(function(event) {
              if(event.which == 3) { // right click
                  window.open("newlocation.html","");
              }
        });
    

    See it live http://jsfiddle.net/8CHTm/1/

    0 讨论(0)
  • 2020-12-09 19:29

    Please take look on sample code. It may help

    <script type='text/javascript'>
        jQuery(function($){
            $('a').mousedown(function(event) {
                switch (event.which) {
                    case 1:
                        //alert('Left mouse button pressed');
                        $(this).attr('target','_self');
                        break;
                    case 2:
                        //alert('Middle mouse button pressed');
                        $(this).attr('target','_blank');
                        break;
                    case 3:
                        //alert('Right mouse button pressed');
                        $(this).attr('target','_blank');
                        break;
                    default:
                        //alert('You have a strange mouse');
                        $(this).attr('target','_self"');
                }
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-12-09 19:33

    You need to also consider that ctrl-click and cmd-click are used to open new tabs (in windows/linux and mac respectively. Therefore, this would be a more complete solution:

    jQuery.isClickEventRequestingNewTab = function(clickEvent) {
        return clickEvent.metaKey || clickEvent.ctrlKey || clickEvent.which === 2;
    };
    
    0 讨论(0)
  • 2020-12-09 19:40

    Please try "_newTab" instead of "_blank"

    window.open( URL , "_newtab");

    0 讨论(0)
  • 2020-12-09 19:42

    The default action of the middle mouse button is to open in a new tab.

    You could set the hyperlinks target attribute to _blank to open a new tab.

    <a href="#link" target="_blank">Link</a>
    

    You can also refer to this question How to distinguish between left and right mouse click with jQuery

    0 讨论(0)
提交回复
热议问题