当我选择 document
、*
、body
或任何特定元素时,Keydown 工作得很好。
但是当我添加 .not('.some-class')
时,keydown 的工作方式就像这样 .not()
甚至不存在。可能是因为 keydown 影响子元素的方式,但我不确定:
$('*').not('.some-class').on('keydown',function(e){
var key = e.charCode || e.keyCode;
if(key == 33 || key == 34 || key == 35 || key == 36 || key == 37 || key == 38 || key == 39 || key == 40 ) {
e.preventDefault();
} else {}
});
如何为除 1 个子类之外的整个文档禁用这些键?
编辑: http://jsfiddle.net/umL139xw/2/
如何在保持使用箭头移动插入符号的能力的同时停止这种不需要的滚动?
edit2:感谢 Jason P 和 Kaiido 的完整解决方案
最佳答案
您可以使用 this answer 中的光标位置检测器 然后 preventDefault()
只有当你在最后。
$(document).on('keydown',function(e){
console.log(this, e.target);
var key = e.charCode || e.keyCode;
if(key == 16 || key == 32 || key == 33 || key == 34 || key == 35 || key == 36 || key == 37 || key == 38 || key == 39 || key == 40 ) {
e.preventDefault();
} else {}
});
$('.b').on('keydown', function(e) {
e.stopPropagation();
var key = e.charCode || e.keyCode;
//Above part comes from https://stackoverflow.com/questions/7451468/contenteditable-div-how-can-i-determine-if-the-cursor-is-at-the-start-or-end-o/7478420#7478420
range = window.getSelection().getRangeAt(0)
post_range = document.createRange();
post_range.selectNodeContents(this);
post_range.setStart(range.endContainer, range.endOffset);
next_text = post_range.cloneContents();
if( next_text.textContent.length === 0 && key == 39 ){
e.preventDefault();
}
});
关于javascript - 在 contenteditable div 中使用箭头键移动插入符号时停止不需要的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270452/