在浏览器 HTML 元素上触发左键单击事件 - 直接从键盘



我希望直接从键盘打开我用鼠标站立的链接(即鼠标光标所在的链接):

相反,我单击鼠标左键以打开光标飞过上方的链接,我只需点击一些键盘组合,然后单击事件将直接触发鼠标光标所在的位置。

我在此列表或此 SE QA 会话中找不到方法。

我的意思不是使用 Tab 键专注于元素并按 CTRL + 输入,或者

document.querySelector('#myElement').click()

您可以使用以下 JavaScript 代码来实现您想要的,而无需修改 HTML 或 CSS。

function listenToShortcut(e) {
  // Change the shortcut to what you desire
  if (e.ctrlKey && e.shiftKey && e.keyCode == 83) {
    e.target.click();
  }
}
var links = document.querySelectorAll('a');
Array.prototype.forEach.call(links, function(link) {
  link.setAttribute('tabindex', '0');
  link.style.outline = 'none';
  link.addEventListener('mouseenter', function(me) {
    link.focus();
    link.addEventListener('keydown', listenToShortcut);
  });
  link.addEventListener('mouseleave', function() {
    link.removeEventListener('keydown', listenToShortcut);
  });
});

在此示例中,快捷方式为 Ctrl + Shift + s 。您可以将其更改为所需的内容。

解释

  • Array.prototype.forEach.call() 是循环访问所有链接元素的解决方法。

  • 将每个链接的属性设置为'0' tabindex允许我们通过使链接可聚焦来侦听链接上的keydown事件

  • 将每个链接的样式属性设置为'none' outline 防止鼠标指针进入链接时在链接周围出现一个丑陋的蓝色框。

  • 当鼠标指针进入链接区域时,我们将链接聚焦为 focus()方法,以便我们可以侦听该链接上的keydown事件。然后我们添加一个事件侦听器,用于侦听keydown事件链接。

这个想法是在整个文档上附加一个事件侦听器以进行鼠标移动并捕获该元素的目标。这样您就知道鼠标悬停在哪个元素上,然后您可以dispatch MouseEvent

请参阅下面的示例(按 G 模拟点击):

(CSS仅用于美学)

let lastMouseElement;
let lastMouseEvent;
document.addEventListener('mousemove', event => {
  if (event.target) {
    lastMouseEvent = event;
    lastMouseElement = event.target;
  }
});
document.addEventListener('keyup', event => {
  if (event.key.toLowerCase() === 'g') {
    if (lastMouseElement && lastMouseEvent) {
      console.log('simulated click');
      lastMouseElement.dispatchEvent(new MouseEvent('click', {
        clientX: lastMouseEvent.clientX,
        clientY: lastMouseEvent.clientY,
        screenX: lastMouseEvent.screenX,
        screenY: lastMouseEvent.screenY,
      }));
    }
  }
});
Array.from(document.querySelectorAll('.container *')).forEach(element => {
  element.addEventListener('click', () => {
    element.classList.add('flash');
    setTimeout(() => element.classList.remove('flash'), 1000);
  });
});
.container {
  height: 100vh;
  width: 100vw;
  background-color: palevioletred;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
}
.left, .right {
  flex: 1;
  margin: 0.5em;
  padding: 0.5em;
  background-color: peachpuff;
  display: flex;
  flex-direction: column;
}
.top, .bottom {
  flex: 1;
  margin: 0.5em;
  padding: 0.5em;
  background-color: papayawhip;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: sans-serif;
  font-size: 1.618em;
}
.flash {
  transition: all 200ms;
  background-color: white;
}
<div class="container">
  <div class="left">
    <div class="top">A</div>
    <div class="bottom">B</div>
  </div>
  <div class="right">
    <div class="top">C</div>
    <div class="bottom">D</div>
  </div>
</div>

最新更新