javascript - 在 contenteditable div 中使用箭头键移动插入符号时停止不需要的滚动

标签 javascript jquery function jquery-selectors keydown

当我选择 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 的完整解决方案

http://jsfiddle.net/umL139xw/5/

最佳答案

您可以使用 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();
    }
});

Working fiddle

关于javascript - 在 contenteditable div 中使用箭头键移动插入符号时停止不需要的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270452/

相关文章:

javascript - 图像轮播不会前进 (HTML/JavaScript)

javascript - Angular-Fullstack 获取当前用户

javascript - CakePhp3 - 在 ChartJs 上显示值

javascript - Jquery:无法将空格添加到 contenteditable div 的占位符

c++ - 正整数之和,使用函数。

jquery - 使用 colSpan 和 rowSpan 将旧表中的行和列克隆到新表中

jquery - 将 div 的高度设置为宽度的一半

javascript - 将隐藏应用于数组中的第一个元素

javascript - 通过返回 false 来阻止链接打开 - 不起作用 (javascript)

javascript - 同时分配和执行 Javascript 函数