Increasing/decreasing 使用 tampermonkey 在按键上显示在网站上的数字

Increasing/decreasing a number displayed on a website on keypress using tampermonkey

我正在尝试创建一个 tampermonkey 脚本,如果按下 =/+ 按钮,网页上的数字会增加 1,当按下 -/_ 按钮时,它会减少 1,然后重置回 0如果按下 0/) 键。

这是我要修改的部分现在的样子:

<div class="toptext"><h1 id="counter">Count: 0</h1></div>

我通过编写以下 tampermonkey 脚本将此文本添加到网站(页面上已经存在 "toptext" class,因此我可以简单地编辑其 innerHTML):

document.getElementsByClassName("toptext")[0].innerHTML = "<h1 id=\"counter\">Count: 0<\/h1>"

所以 0 需要变成一个变量,我可以通过按下这些键来随意更改。 遗憾的是,我的编码知识非常有限,所以虽然看起来应该不难做到,但我就是不知道如何编写工作代码。

我已经尝试找到类似的脚本,所以我可以复制其中的一些部分并将某些内容拼接在一起,但我仍然没有太多可以使用的东西。

这是我现在拥有的:

//First I need to create a variable with starting value of 0
var variable = 0;

//Now I need functions to increase and decrease this variable, and update the counter accordingly
function increase() {
//increase variable by 1
variable = variable+1;
//update counter
document.getElementsByClassName("toptext")[0].innerHTML = "<h1 id=\"counter\">Count: <insert variable here><\/h1>"
}

function decrease() {
//decrease variable by 1
variable = variable-1;
//update counter
document.getElementsByClassName("toptext")[0].innerHTML = "<h1 id=\"counter\">Count: <insert variable here><\/h1>"
}

function reset() {
//reset the variable back to 0
variable = 0;
//update counter
document.getElementsByClassName("toptext")[0].innerHTML = "<h1 id=\"counter\">Count: <insert variable here><\/h1>"
}

//now I need event listeners to execute these functions if one of the keys is hit
document.addEventListener('=', increase, false);
document.addEventListener('-', decrease, false);
document.addEventListener('0', reset, false);

如果有人能把它变成一个工作脚本,我们将不胜感激。

您需要使用 keypress 事件侦听器。 JS 不提供单独的按键事件侦听器,您只能使用 keyupkeydownkeypress.

document.addEventListener('keypress', (e) => {
    switch (e.key) {
        case '=':
            increase();
            break;
        case '-':
            decrease();
            break;
        case '0':
            reset();
            break;
    }
});

完整代码如下所示:

let variable = 0;

function updateVariable(newVariable) {
    variable = newVariable;
    document.getElementsByClassName("toptext")[0].innerHTML = `<h1 id="counter">Count: ${variable}</h1>`;
}

document.addEventListener('keypress', (e) => {
    switch (e.key) {
        case '=':
            updateVariable(variable + 1);
            break;
        case '-':
            updateVariable(variable - 1);
            break;
        case '0':
            updateVariable(0);
            break;
    }
});
<div class="toptext"><h1 id="counter">Count: 0</h1></div>

还有一个潜在的问题,在设置 innerHTML 时,您需要 100% 确保不包含来自外部源的变量(例如查询字符串,或者 API 您无法控制的变量)。如果您不信任来源,请使用 innerText。在这种情况下,您的 variable 看起来值得信赖,但这需要以后考虑。