caret position in an editable div (dartlang)

点点圈 提交于 2019-12-25 04:42:50

问题


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:


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



来源:https://stackoverflow.com/questions/21730134/caret-position-in-an-editable-div-dartlang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!