【问题标题】:How to override default alt-key + click action? Browser makes a download, but如何覆盖默认的 alt 键 + 单击操作?浏览器进行下载,但
【发布时间】:2018-11-30 19:52:55
【问题描述】:

通过按 alt 键并单击 url,chrome 会进行下载。这是因为浏览器默认的 alt+click 操作。我怎样才能防止这种情况?它应该交换网址。

该代码适用于浏览器没有默认操作的其他键(例如 x == 88)。但是如何使用 alt 键呢?

 //ALT-key recognition
    document.onkeydown=function(){
        var keyCode = event.keyCode;
		if(keyCode == 18) //alt-key
        {
            console.log(keyCode);
			
	    document.getElementById("hist").setAttribute ('href', "history_by-date.php?wdate=all");
        }
    }
 <div id="history"> 			                                
   	 <a href="history_by-date.php?wdate=2018&until=2017" id="hist"  target="_self" class="a2">should be just a link - not a download (when alt is pressed)</a>
     </div><!-- end history -->

skyline3000 的另一个用户有一个有趣的article 带有阻止代码,但我让它不起作用。感谢您的帮助。

evt.preventDefault();
evt.stopPropagation();
return false;

【问题讨论】:

    标签: javascript google-chrome browser keyboard-shortcuts


    【解决方案1】:

    我认为您需要听链接点击事件并检查 event.altKey 属性,而不是听按键。如果这是防弹与 alt-click 下载,我不是 100%,但它似乎有效。请注意,使用this.click() 调用链接只有在正常的href、没有javascript 或点击事件的情况下才有效。否则,还有其他更复杂的方法可以完成该部分。

    document.querySelectorAll('a').forEach(a => {
      a.addEventListener('click', function (e) {
        if (e.altKey) {
          e.preventDefault(); // no download
          this.href = 'history_by-date.php?watchdate=all';
          this.click(); // fake a normal click
        }
      });
    });
    &lt;a href='http://example.com'&gt;alt-click me&lt;/a&gt;

    【讨论】:

    • 感谢新观点。为了 href 我添加了 id="hist" 并在 js 中我交换了 this.Click(); with document.getElementById("hist").setAttribute('href', "history_by-date.php?watchdate=all");
    • 在 JsFiddle 中它部分工作,但新的 url 仅在点击后显示。不幸的是,在我的网站上它没有任何反应。它也在下载。但我会更深入地理解你的观点。
    • 不,您不能只在该函数中设置 href 属性,您还必须使用我展示的 click() 技巧或 window.location.href = 'history_by-date.php?watchdate=all' 之类的方法使浏览器也访问该 url - 试试我所做的改变。
    【解决方案2】:

    您的要求是更改用户浏览器的默认操作。这是不可能的。来自浏览器的默认操作不会在 HTML DOM 中运行,因此无法检测到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 2014-05-30
      • 2018-02-21
      • 2011-06-30
      • 1970-01-01
      相关资源
      最近更新 更多