caret position in an editable div (dartlang)

2019-09-09 09:15发布

I try to find the caret position in an editable div. Also it should be nice to get the selected text in this div.

I try to assimilate this: Editable Div Caret Position

But it dosen’t work.

I'll be happy to give any Idea.

Thanks in advance

Some code snippet

HTML

<a on-click="{{chooseMenu}}" which-menu="1">Menu 1</a>

Dart

  void chooseMenu(Event event, var detail, var target) {

    event.preventDefault();
    event.stopPropagation();

    Selection sel;
    Range range;

    sel = window.getSelection();

    if(sel != null) {
      range = sel.getRangeAt(0);
      range.collapse(false);
    }

    currentSubMenu = int.parse(target.attributes['which-menu']);
  }

1条回答
叛逆
2楼-- · 2019-09-09 10:02

This worked for me in Dartium.

The other code from the referenced SO question is probably to support other browsers. Dart usually generates JS code that works in all supported browsers. You have to test yourself if the generated JS really works in the browsers you want to support.

EDIT

We store the selection whenever it changes. Maybe there are better events but I couldn't find one. But it worked fine for me. We insert the new node at the previously stored selection.

// must be accessible by getRange, insertNodeAfterSelection 
DivElement editable;
Range range;

// store reference to our contenteditable element
editable = (document.querySelector('#editable') as DivElement);

// subscribe selection change events
document.onSelectionChange.listen(getRange);


void insertNodeAfterSelection(Node node) {
  range.collapse(false);
  range.insertNode(node);
}

void getRange(Event e) {
  if(document.activeElement != editable) { // save only selection changes on our contenteditable
    return;
  }
  print(e);
  Selection sel;

  sel = window.getSelection();
  if(sel != null) {
    range = sel.getRangeAt(0);
  }
}

You have to decide yourself where you put those code parts. I added some comments as support.

EDIT
using the mousedown event instead of click should help around this issue
Preserve text selection in contenteditable while interacting with jQuery UI Dialog and text input

查看更多
登录 后发表回答