【发布时间】:2016-07-19 21:35:45
【问题描述】:
一个简单的 html 页面只包含两个控件,一个文本框和一个按钮。页面加载后,如果用户在文本框内单击并按“alt”+p(按钮访问键),则消息应显示为“I'm from key down!!!”但是,如果用户单击文本框内以外的任何位置,则消息应显示为“仅当焦点位于文本框外时才应调用我!!!”。完整代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function keyDown() {
if (event.altKey && event.keyCode == 80) {
event.returnValue = false;
event.cancelBubble = true;
event.keyCode = 0;
alert("I'm from key down!!!");
}
}
function clickMe() {
alert("I should be called only when the focus is outside the textbox!!!");
}
</script>
</head>
<body>
<div>
<input type="text" onkeydown ="keyDown();" />
<input type="button" value="Click me" accesskey="p" onclick="clickMe();" />
</div>
</body>
</html>
在 IE10 及以下版本中运行良好。但它在 IE11 和 Chrome 中不起作用,而是一个接一个地显示两条警报消息,例如“我从按键按下!!!”和“只有当焦点在文本框之外时才应该调用我!!!”这是不可取的。所以 keyDown() 事件处理程序被更改为支持 IE10+ 和 Chrome 之类的
function keyDown() {
if (event.altKey && event.keyCode == 80) {
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
event.stopPropagation ? event.stopPropagation() : (event.cancelBubble = true);
event.keyCode = 0;
alert("I'm from key down!!!");
}
}
但是在这种情况下 event.stopPropagation() 不起作用,知道为什么吗?
【问题讨论】:
-
你怎么知道
stopPropagation不起作用? -
因为两条警报消息都被触发了。
-
“因为两条警报消息都被触发了。” 只有一个事件处理程序正在侦听
keydown事件。停止传播意味着不会触发附加到<input>元素的 ancestor 的另一个keydown事件处理程序。也许与其告诉我们什么“行不通”,不如解释一下你想做什么。 -
在文本框外聚焦不应触发 clickMe(),因为它只绑定到按钮的点击事件。
-
@YoannM:
event在 IE 和 Chrome 中是全局的。
标签: javascript html browser