文档键盘事件传播给有停止propapagation的输入儿童
我对文档事件键盘有问题。 当我按下细节键(1或2)时,事件键down会传播输入子。 我使用了event.stoppropagate(),但我不起作用。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TEST KEYDOWN EVENT</title>
</head>
<body>
<form>
<label>Number of Series</label>
<input type="number" name="nbSeries" value="10" id="nbSeries"/>
</form>
<script type="text/javascript">
document.addEventListener('keydown', keyPressed);
function keyPressed(e){
e.stopPropagation();
if(e.code == "Digit1" || e.code == "Digit2"){
console.log('You pressed ' + e.code);
}
}
</script>
</body>
</html>
在控制台上,当我使用键1和2更改输入(#nbseries)值时,显示: 您按了“键盘” ...
I have a problem with document event keydown.
When i pressed on specifics keys (1 or 2), the event keydown propagates to input child.
I used event.stopPropagate() but i doesn't work.
Here my code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TEST KEYDOWN EVENT</title>
</head>
<body>
<form>
<label>Number of Series</label>
<input type="number" name="nbSeries" value="10" id="nbSeries"/>
</form>
<script type="text/javascript">
document.addEventListener('keydown', keyPressed);
function keyPressed(e){
e.stopPropagation();
if(e.code == "Digit1" || e.code == "Digit2"){
console.log('You pressed ' + e.code);
}
}
</script>
</body>
</html>
On console, when i change my input (#nbSeries) value using key 1 and 2, display :
You pressed "keyCode"...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
stoppropagation
仅阻止事件传播 - 以后阻止其他听众看到事件。这确实不是停止操作的默认行为。例如,它在输入输入字段时不会阻止字符出现。为了实现这一目标,您需要预防违规
。另外,尽管它与您遇到的问题没有直接关系,但对于事件传播的工作方式也有一些牢记。 以下顺序触发:
听众按 Document Keydown的听众正在聆听冒泡的事件,仅在活动到达目标的听众之后,它才会触发。 如果您试图在文档上有一个听众在子元素上阻止侦听器触发,则需要在捕获阶段添加文档侦听器,以防止向下传播到目标,可以通过将
true
传递给AddeventListener
的第三个参数来完成。stopPropagation
only stops the event from propagating - stopping other listeners later from seeing the event. That does not stop the default behavior of the action. For example, it doesn't stop characters from appearing when typing into an input field. To achieve that, you needpreventDefault
instead.Also, although it's not directly related to the problem you were experiencing, there's also something to keep in mind about how event propagation works. Listeners trigger in this order:
Since your document keydown listener is listening for bubbling events, it triggers only after the event's reached the target's listeners. If you were trying to have a listener on the document stop a listener on a child element from triggering, you would need to add the document listener in the capturing phase instead to prevent propagation downwards to the target, which can be done by passing
true
toaddEventListener
's third parameter.