![](/img/trans.png)
[英]append a span at caret in contenteditable div when I click on another div
[英]Stop unwanted scrolling when moving caret with arrow keys in contenteditable div
当我选择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
事件冒泡(嗯,其中很多确实如此)。 这意味着它们会在事件的目标上触发,然后在DOM树上的每个元素上触发,因此即使您不将处理程序绑定到.some-class
,它也会为该元素的祖先触发。 另外,将事件处理程序绑定到*
通常不是一个好主意。 也许这样的事情适合您?
$(document).on('keydown',function(e){
console.log(this, e.target);
});
$('.some-class').on('keydown', function(e) {
e.stopPropagation();
});
您可以从此答案中使用光标的位置检测器,然后仅在最后时才使用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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.