[英]event.preventDefault() works on Chrome, Firefox, but not Safari
This HTML / JS code : 此HTML / JS代码:
<script>
window.onload = function(e) {
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
event.preventDefault();
alert("hello");
return false;
}
}
}
</script>
<p>Blah</p>
overrides the browser CTRL+PLUS 's ZOOM keyboard shortcut. 覆盖浏览器CTRL + PLUS的ZOOM键盘快捷键。
It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the alert("hello")
is launched, but the browser's zooming is also changed ! 它可以在Firefox,Chrome上运行,但不能在Safari上运行:在Safari上,如果在此页面上执行CTRL + PLUS,将启动
alert("hello")
,但浏览器的缩放比例也会改变!
This means that event.preventDefault();
这意味着
event.preventDefault();
hasn't worked like it should have worked. 没有像它应该的那样工作。
How to use event.preventDefault()
with Safari ? 如何在Safari中使用
event.preventDefault()
?
Note: I already tried as well with StopPropagation, but it doesn't solve the problem. 注意:我已经尝试过StopPropagation,但是它不能解决问题。
Seems like this is problem with ctrlKey
. 似乎这是
ctrlKey
问题。 Assuming you use Mac OS X system you need to check for metaKey
too, so your code should be: 假设您使用Mac OS X系统,则也需要检查
metaKey
,因此您的代码应为:
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 61 || event.keyCode == 187))
We probably have different keyboard layouts or something, but my +
and -
signs on my numpad have the key code values 107 and 109. ( http://www.asquare.net/javascript/tests/KeyCode.html ) 我们的键盘布局可能有所不同,但是数字键盘上的
+
和-
号具有键代码值107和109。( http://www.asquare.net/javascript/tests/KeyCode.html )
The code snippet below works in safari for me. 下面的代码段对我来说适用于野生动物园。
window.onkeydown = function (event) { if (event.ctrlKey && (event.keyCode == 107 || event.keyCode == 109)) { event.preventDefault(); alert("hello"); } }
You can try this: 您可以尝试以下方法:
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
if (event.preventDefault){
event.preventDefault();
}
else {
event.returnValue = false;
}
alert("hello");
return false;
}
}
}
The key codes for zoom are different across browsers: 缩放的关键代码在不同的浏览器中有所不同:
Opera MSIE Firefox Safari Chrome
61 187 107 187 187 = +
109 189 109 189 189 - _
Also try : 也可以尝试:
event.stopImmediatePropagation();
To prevent other handlers from executing. 防止其他处理程序执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.