使用DIV作为链接触发新选项卡快捷方式的重定向

Using DIV as link triggers redirect on new tab shortcut

本文关键字:选项 快捷方式 重定向 新选项 DIV 链接 接触 使用      更新时间:2023-09-26

我有一个页面(小部件)的一部分,我想用它作为一个链接(点击任何地方都会去到不同的页面):

<!-- just an example. real application is quite a bit more complex -->
<div data-href="/page">
   <h1><a href="/page">Title of sample content</a></h1>
   <p>
        some content here with an image
        <img src="image.jpg">
   </p>
   <div>
        and many more elements in here
        <div>
             with nested structure with semantic meaning
        </div>
   </div>
</div>

由于该部分是<div>,我不能围绕<a>包装,因为这是违反HTML规范的。我也不能将divs更改为span,因为它们实际上具有语义意义。

目前我附加了一个JS click事件,我改变了浏览器的位置,有效地作为一个链接:

$('div').click(function() {
    window.location=$(this).data("href");
});

这工作正常,除非当你Ctrl+ClickCmd+Click<a>上打开新的选项卡中的链接。由于此时您没有显式地进行右键单击,因此浏览器将其注册为单击,因此函数无论如何都会执行。

我想我可以检查是否有任何修改键按在点击事件,但我觉得这是有点麻烦。有一个很好的JS解决方案吗?

你可以这样做(jQuery为点击处理程序):

$(selector).click(function(e) {
  if(e.shiftKey) {
    //Shift-Click
  }
  if(e.ctrlKey) {
    //Ctrl+Click
  }
  if(e.altKey) {
    //Alt+Click
  }
});

你可以在点击处理程序中的if中处理任何你想要的,如上面所示