使用cmd-key打开新标签中的链接?

时间:2017-04-07 23:47:24

标签: javascript jquery macos keyboard

我使用它来点击一个元素来打开一个链接。当我按住cmd键时(以及其他OS中反映的内容),有没有办法让它打开一个新选项卡?

$(document).on('click', '.row', function(e) {
    e.preventDefault();
    window.location = '?id=' + $(this).data('id');
});

基本上普通<a>的工作方式,但通过JS。

2 个答案:

答案 0 :(得分:1)

当然,除了点击处理程序之外,你只需要跟踪你的目标键是否被按下:

document.querySelector('#test').addEventListener('click', function(e) {
  if(cmdPressed) {
      console.log('new tab');
      // window.open('');
  } else {
      console.log('redirect');
      // location.href = '';
  }
})

// keeps track of whether user is pressing cmd key
var cmdPressed = false;

document.body.addEventListener('keydown', function(e) {
    cmdPressed = e.which === 91;
});

document.body.addEventListener('keyup', function(e) {
    cmdPressed = false;
});
<div id="test">
Click or CMD+Click me
</div>

或使用jQuery:

$(document).on('click', '#test', function(e) {
   e.preventDefault();
   if(cmdPressed) {
      console.log('new tab');
      // window.open('');
   } else {
      console.log('redirect');
      // location.href = '';
   }
});

// keeps track of whether user is pressing cmd key
var cmdPressed = false;

$(document).on('keydown', function(e) {
    cmdPressed = e.which === 91;
});

$(document).on('keyup', function(e) {
    cmdPressed = false;
});

答案 1 :(得分:0)

试试这个:

$(document).on('click', '.row', function(e) {
  e.preventDefault();
  if (cmd) window.open('?id=' + $(this).data('id'), "_blank");
  else window.location = '?id=' + $(this).data('id');
});
var cmd = false;
$(document).keydown(function(e) {
  var key = e.which || e.keyCode;
  if (key == 91 || key == 93 || key == 17 || key == 224) cmd = true;
});
$(document).keyup(function(e) {
  cmd = false;
});
.row { border: 1px #000 solid }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">Click Me</div>