簡體   English   中英

在contenteditable 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

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

事件冒泡(嗯,其中很多確實如此)。 這意味着它們會在事件的目標上觸發,然后在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(); 
});

您可以從此答案中使用光標的位置檢測器,然后僅在最后時才使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM