Vanilla JavaScript:在网页中禁用给定的预先存在的键组合 [英] Vanilla JavaScript: Disabling a given preexisting key-combo in a webpage

查看:78
本文介绍了Vanilla JavaScript:在网页中禁用给定的预先存在的键组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此随机英语 - 维基百科编辑页面可以添加一些内容(比如测试),然后通过 Alt + Shift + S 的预先存在的键组合保存它。

In this random English-Wikipedia edit page one can add some content (say "test"), then saving it by the preexisting key-combo of Alt+Shift+S.

我希望阻止此行为具体(不使用 document.querySelector(#wpSave)删除保存按钮.remove() ; )。

I desire to prevent this behavior specifically (without removing the save button with document.querySelector("#wpSave").remove();).

我尝试了以下失败的代码:

I tried the following code that failed:

// ==UserScript==
// @name         wiki
// @match        https://*.wikipedia.org/*
// ==/UserScript==

document.addEventListener("DOMContentLoaded", ()=>{
    document.addEventListener('keypress', function(e) {
        if (e.key == 16 && e.key == 18 && e.key == 83) {
            return false;
        }
    });
});

我还尝试用<替换返回false code> e.preventDefault()或 evt.stopPropagation(),但都失败了(没有控制台错误)。

I also tried replacing return false with e.preventDefault() or evt.stopPropagation(), but all failed (no console errors).

代码有什么问题?

注意:此问题与此问题不同通常侧重于禁用给定的预先存在的键组合功能,而不是一般禁用保存功能

Note: This question differs from this one by focusing on disabling a given preexisting key-combo functionality in general, and not on saving functionalities in general.

我在控制台中使用了这个,但我仍然遇到同样的问题:

I used this in console but I still have the same problem:

document.addEventListener("DOMContentLoaded", ()=>{
    const state = {};
    document.addEventListener('keydown', function(e) {
        state[e.key] = true;
    });

    document.addEventListener('keyup', function(e) {
        state[e.key] = false;
    });

    document.addEventListener('keyup', function(e) {
        state[e.key] = false;
        if (state["Alt"] && state["Shift"] && (state["S"] || state["s"])) {
            return e.preventDefault();
        }
    });
});


推荐答案

一次只能出现一个关键事件,所以你必须创建一个状态机来确定哪些是打开和关闭的。
考虑一下:

Only one key event will be present at a time, so you have to create a state machine to determine which ones are on and off. Consider this:

const state = {};
document.addEventListener('keydown', function(e) {
  state[e.key] = true;
});


document.addEventListener('keyup', function(e) {
  state[e.key] = false;
});

现在,您可以检查所需的密钥是否一次全部被按下,然后防止最后一个按键向下滴下DOM。

Now with this, you can check if your desired keys are all being pushed down at one time, then prevent the last keypress from trickling down the DOM.

document.addEventListener('keyup', function(e) {
  state[e.key] = false;
  if (state["Alt"] && state["Shift"] && (state["S"] || state["s"])) {
    return e.preventDefault();
  }
});

这篇关于Vanilla JavaScript:在网页中禁用给定的预先存在的键组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆