![](/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.