Contenteditable DIV - how can I determine if the cursor is at the start or end of the content

后端 未结 5 823
一整个雨季
一整个雨季 2020-12-03 02:04

I have a contenteditable div which contains typical wysiwyg editor html (bold, anchors, lists).

I need to determine if the current cursor is, onKeyDown, at the start

5条回答
  •  日久生厌
    2020-12-03 02:12

    This is how I ended up solving this. My proposed solution above worked sometimes but there were way to many edge cases, so I ended up considering how much text was before or after the cursor, and if that was 0 characters, then I was at the start or end:

    handle_keydown = function(e) {
      // Get the current cusor position
      range = window.getSelection().getRangeAt(0)
      // Create a new range to deal with text before the cursor
      pre_range = document.createRange();
      // Have this range select the entire contents of the editable div
      pre_range.selectNodeContents(this);
      // Set the end point of this range to the start point of the cursor
      pre_range.setEnd(range.startContainer, range.startOffset);
      // Fetch the contents of this range (text before the cursor)
      this_text = pre_range.cloneContents();
      // If the text's length is 0, we're at the start of the div.
      at_start = this_text.textContent.length === 0;
      // Rinse and repeat for text after the cursor to determine if we're at the end.
      post_range = document.createRange();
      post_range.selectNodeContents(this);
      post_range.setStart(range.endContainer, range.endOffset);
      next_text = post_range.cloneContents();
      at_end = next_text.textContent.length === 0;
    }
    

    Still not entirely sure there are any other edge cases, as I'm not entirely sure how to unit test this, since it requires mouse interaction - there's probably a library to deal with this somewhere.

提交回复
热议问题