简体   繁体   中英

My keyboard event shortcut isn't firing and I don't know why

I have a main area which is editable. i want the user to be able to create bullet point hierarchies of notes. A user creates a new paragraph by pressing enter (this part works). However, if they press 'end' (keycode 35) the paragraph becomes an li element and it becomes a child of its parent element. I can never get the event to fire and I don't know what I'm doing wrong. Should be able to look like this:

let m=document.getElementById('textEdit'); //main area
     function mKeyClick(e){
     if (e.keyCode=="13"){ //enterKey
        e.preventDefault();
        let p=document.createElement("p");
        p.addEventListener("keypress",pKeyClick);
        m.appendChild(p);
        //...

    function pKeyClick(e){
    if (e.keyCode=="35"){ //end key
    e.preventDefault();
    let parent=e.target.parentNode;
    let li=document.createElement("li");
    parent.replaceChild(li,e.target);
    e.stopPropagation();
  }
}

Should be able to look like this:

  • descrition
    • more fine tuned details

Try different approach - instead of adding new event listener to child element, handle all event with single handler that is bound to parent textEdit element.

I prepared a snippet that handles your requirements: https://jsfiddle.net/cf0ju28s/

Note: since I'm on Mac and don't have end key, I used tab key instead.

let textEdit = document.getElementById('textEdit'); //main area

function mKeyClick(e) {
  if (e.keyCode == 13) { //enterKey
    e.preventDefault();

    // create paragraf
    let p = document.createElement("p");
    p.innerHTML = ' '; // add content, need to focus later
    textEdit.appendChild(p);

    // select paragraph content - enables you to write in it
    var range = document.createRange();
    var sel = window.getSelection();
    range.selectNode(p);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (e.keyCode == 9) { // tab key
    e.preventDefault();

    // find tag at caret position
    let target = window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode;

    // change p tag to li tag + check that we have actual tag, not root textEdit element
    if (target != textEdit && target.innerHTML != '') {
      let li = document.createElement("li");
      li.innerHTML = target.innerHTML;
      target.parentNode.replaceChild(li, target);
    }
  }
}


textEdit.addEventListener("keydown", mKeyClick);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM