【问题标题】:Stop unwanted scrolling when moving caret with arrow keys in contenteditable div在 contenteditable div 中使用箭头键移动插入符号时停止不需要的滚动
【发布时间】:2014-10-05 21:15:13
【问题描述】:

当我选择 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/

【问题讨论】:

  • 试试$('*:not(.some-class)')

标签: javascript jquery function jquery-selectors keydown


【解决方案1】:

事件冒泡(嗯,有很多)。这意味着它们会在事件的目标上触发,然后在 DOM 树上的每个元素上触发,因此即使您没有将处理程序绑定到 .some-class,它也会为该元素的祖先触发。此外,将事件处理程序绑定到* 通常不是一个好主意。也许这样的东西对你有用?

http://jsfiddle.net/j3wqpdow/

$(document).on('keydown',function(e){ 
    console.log(this, e.target);
});

$('.some-class').on('keydown', function(e) {
   e.stopPropagation(); 
});

【讨论】:

  • 这在小提琴中有效。但是,键仍然会影响页面(滚动)。如何预防?
  • 你能创建一个演示这个问题的小提琴吗?
  • 这里是 - jsfiddle.net/umL139xw/1 有效,但我想删除的滚动问题仍然存在。也许我应该重新提出这个问题。编辑:按住右箭头。
  • Chrome 不会滚动页面,但是在 Firefox 中,使用 B(使用 stopPropagation),当到达文本末尾时它会滚动页面。
【解决方案2】:

您可以使用 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

【讨论】:

  • 太棒了!如果有人想知道如何禁用密钥,例如。向上翻页,无论位置如何,都可以这样做:if( next_text.textContent.length === 0,1 && key == 34 )
猜你喜欢
  • 2018-12-13
  • 2014-01-29
  • 2017-04-28
  • 2012-02-06
  • 2020-02-20
  • 2011-03-13
  • 1970-01-01
  • 2015-03-11
  • 2013-08-25
相关资源
最近更新 更多