【问题标题】:Programmatically press keys on webpage using javascript使用 javascript 以编程方式在网页上按键
【发布时间】:2021-01-04 21:29:47
【问题描述】:

尝试使用下面的 sn-p 创建 keydown 事件。 keypress 函数触发,但该值未添加到文本框中。我想使用键编辑文本框 1 的值。

fyi - 故意避免直接设置 element.value


    <html>
    
    <head>
        <script>
            function f1() {
                document.querySelector("#text1").focus()
                document.querySelector("#text1").onkeydown = test;
                var keypress = new KeyboardEvent("keydown", {
                    key: "e",
                    keyCode: 69, // example values.
                    code: "KeyE", // put everything you need in this object.
                    which: 69,
                    shiftKey: false, // you don't need to include values
                    ctrlKey: false,  // if you aren't going to use them.
                    metaKey: false   // these are here for example's sake.
                })
                console.log("srcElement" + keypress.srcElement);
                console.log("currentTarget" + keypress.currentTarget);
                var element = document.getElementById("text1")
                element.dispatchEvent(keypress);
                console.log("srcElement" + keypress.srcElement);
                console.log("currentTarget" + keypress.currentTarget);
            }
            function test(e) {
                console.log("Called" + e.key);
                console.log("Called" + e.keyCode);
            }
        </script>
    
    </head>
    
    <body onload="f1()">
        <form>
            Input 1 : <input type="text" id="text1" name="text1" />
    
            Input 2 :<input type="text" id="text2" name="text2" />
        
        </form>
    </body>
    
    </html>

这是控制台上的输出:

test.html:17 srcElementnull
test.html:18 currentTargetnull
test.html:25 Callede
test.html:26 Called69
test.html:21 srcElement[object HTMLInputElement]
test.html:22 currentTargetnull

【问题讨论】:

  • 没用是什么意思?你得到什么错误?
  • 有人在这里问过类似的问题:stackoverflow.com/questions/65558501/…
  • 您是否希望这些事件也改变元素的值?因为它不是那样工作的。事件就是事件,值就是 JavaScript 中的值。通过简单地调度一个事件,值不会改变。

标签: javascript


【解决方案1】:

如果我理解这个问题,我想you can do

document.addEventListener('keypress', (evt) => {
  console.log(`code = ${evt.keyCode}`);
});

var keyboardEvent = new KeyboardEvent('keypress', {bubbles:true, 'keyCode': 48});

document.dispatchEvent(keyboardEvent); 

但是您不能将keyboardEvent 用于您的目的。 来自@zero298 中的this answer

注意:手动触发事件不会生成默认操作 与该事件相关联。例如,手动触发按键事件 不会导致该字母出现在焦点文本输入中。在里面 UI 事件的情况下,出于安全原因,这很重要,因为它 防止脚本模拟与 浏览器本身。

【讨论】:

  • 是的,尝试完全相同。但我想通过输入文本框发送它,并让值在文本框中更新。
  • 我在回答你之前的问题。编辑后,我可以建议阅读stackoverflow.com/questions/50219800/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多