// ==UserScript== // @name Mouse Click Behavior // @namespace http://tampermonkey.net/…
- User
// ==UserScript== // @name Mouse Click Behavior // @namespace http://tampermonkey.net/ // @version 0.1 // @description Single click to open in the current page, double click to open in a new page. // @author You // @match :///* // @grant none // ==/UserScript==
(function() { let clickCount = 0; let singleClickTimer; let ctrlDown = false;
code// 监听键盘按下事件 document.addEventListener("keydown", function(event) { if (event.key === "Control") { ctrlDown = true; } }); // 监听键盘松开事件 document.addEventListener("keyup", function(event) { if (event.key === "Control") { ctrlDown = false; } }); document.addEventListener("click", function(event) { // 如果ctrl键被按下,不执行任何操作 if (ctrlDown) { return; } // 只有当点击的是链接时,才执行下面的逻辑 if (event.target.tagName.toLowerCase() === 'a' && event.target.href) { event.preventDefault(); clickCount++; if (clickCount === 1) { singleClickTimer = setTimeout(function() { clickCount = 0; window.location.href = event.target.href; }, 213); } else if (clickCount === 2) { clearTimeout(singleClickTimer); clickCount = 0; window.open(event.target.href, "_blank"); } } }, false);})();
为什么以上油猴代码在哔哩哔哩网站上不能点击取消连播的按钮,请逐步分析并改正代码
- Assistant
该油猴脚本主要功能是单击链接在当前页面打开,双击链接在新标签页打开。但是哔哩哔哩(Bilibili)网站的"取消连播"按钮不是一个普通的链接(
<a>标签),它可能是一个按钮 (<button>) 或者其他可点击的元素(例如<div>)。脚本中对事件是这样进行处理的:
- 当用户在没有按下Control键的情况下点击了一个
<a>标签时,脚本会阻止默认行为(即跳转链接),并设置一个单击计数器。 - 在第一次点击后,设置一个延时,在213毫秒后将当前页面跳转到链接地址,除非用户在这段时间内再次点击链接,触发第二次点击。
- 如果发生第二次点击,脚本会取消之前的延时,并在新标签页中打开链接。
- 当用户在没有按下Control键的情况下点击了一个