如果您在 OSX 中按住一个键,您会看到一个弹出窗口,您可以在其中选择不同的字符。 我写了一个小网络工具:http://kasperpeulen.github.io/PressAndHold/做完全相同的事情,但我在弹出窗口中添加了许多数学符号。 现在我想覆盖原生 OSX 工具。我试过的是:
$('input').on('keydown', function (e) {
e.preventDefault();
});
演示:http://jsfiddle.net/nggnjo5a/2/
在 Firefox 中,这会覆盖 native OSX 工具。在 chrome 和 safari 中,遗憾的是没有。有没有其他方法可以确保 native OSX 应用程序在我的网站上被禁用?
最佳答案
我很幸运地将 type="text"
字段转换为 type="password"
字段并很快又变回原样。我注意到在密码字段中按住某个键不会触发重音弹出窗口,因此我想利用这种行为。这个技巧并非在 100% 的情况下都有效,而且它是一个丑陋的 hack——但总比没有好。下面是我正在使用的完整代码。我在输入字段的第一个焦点事件上运行它。
this.disableAccentPopup = function(_input, callback){
var last_key_down = false; // last key pressed
var last_key_count = 0; // number of keydown events for last key pressed
var keys_down = {}; // all keys being held down
var input = _input.cloneNode(true); // We will swap this with the original input on first focus
input.type = "password"; // Password fields don't suffer from accent UI
input.value = ''; // Empty this so we don't see the password bullets
input.focus();
// Right before focus...
_input.addEventListener("focus", function(e){
// This setTimeout is needed so we can get the proper selectionStart and selectionEnd values
setTimeout(function(){
var t = _input.value;
var s = _input.selectionStart;
var e = _input.selectionEnd;
_input.parentNode.replaceChild(input, _input);
input.focus();
// This setTimeout is needed to set the input type w/o breaking the input's behavior
setTimeout(function(){
input.value = t;
input.type = 'input';
input.setSelectionRange(s, e);
if (callback) {
setTimeout(function(){
callback(input);
}, 0);
}
}, 0);
}, 0);
});
input.addEventListener("keydown", function(e){
keys_down[util.keyIdentifierToKeyCode(e)] = true;
if (!e.metaKey && e.keyIdentifier.substr(0,2) == "U+") {
if (last_key_down && last_key_count >= 1) {
// if this is not the first keydown event for this char,
// we can safely set the type to input
input.type = 'input';
if (last_key_down == util.keyIdentifierToKeyCode(e)) {
e.preventDefault();
} else {
last_key_count = 0;
}
}
last_key_down = util.keyIdentifierToKeyCode(e);
last_key_count++;
}
});
input.addEventListener("keyup", function(e){
delete keys_down[util.keyIdentifierToKeyCode(e)];
if (!e.metaKey) {
// if _all_ keys are up
if (Object.keys(keys_down).length == 0) {
last_key_down = false;
last_key_count = 0;
}
}
});
}
关于javascript - 在浏览器中覆盖 OSX 按住重音选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25832856/