【问题标题】:How to get the selected text or the inner html in Dart如何在 Dart 中获取选定的文本或内部 html
【发布时间】:2014-11-14 09:18:07
【问题描述】:

如何使用 dart:html 获取当前选择的文本或内部 html?我使用 div 的 on-mouseup 事件作为起点:

<div on-mouseup="{{on_mouseup}}">
void on_mouseup(MouseEvent e, var detail, DivElement src) {
  final selection = window.getSelection();
  // do somthing 
  // ..
  // final selectedText = ..;

  window.alert("Selected text is $selectedText!");
}

例子:

变量selectedText的值应该是'window.getSel'

【问题讨论】:

  • 您的事件处理程序参数列表似乎有点奇怪。传递的参数是eventdetail(与event.detail相同)*和target(与event.target相同)*。 (* - 如果不涉及 dart-js-interop 则相同,例如使用 core-elements 或 paper-elements 时)
  • querySelector() 是另一种选择。

标签: dart dart-polymer dart-html


【解决方案1】:
src.innerHtml` or `src.text
print(window.getSelection().getRangeAt(0).cloneContents().innerHtml);
print(window.getSelection().getRangeAt(0).cloneContents().text);

PolymerElement 中还有一个shadowRoot.getSelection()

print(shadowRoot.getSelection().getRangeAt(0).cloneContents().innerHtml);
print(shadowRoot.getSelection().getRangeAt(0).cloneContents().text);

我在自定义元素之外、在元素的影子 DOM 中以及作为自定义元素的子元素中尝试了它。

There are some issues what can be selected when the selection crosses the shadow boundary (immediately selects the entire content of the shadow DOM. Beside from that document.getSelection() and shadowRoot.getSelection() always return the same result.

似乎getSelection 在结束(鼠标向上)位于影子 DOM 内时不起作用。 When the selection starts in the shadow DOM and ends in the (child) content it works but not the other way around.

我认为这是一个错误。

【讨论】:

  • 我会得到唯一选定的文本。请查看上面更新的问题。
  • 我忘记了大括号()。如果我的答案中的代码不起作用,请尝试window.getSelection().toString()
  • 它返回“'Selection'的实例”字符串。
  • 我明白了。我去看看。
  • 可能是因为它位于 Polymer 元素内。我只是在没有聚合物的 Dart HTML 页面上尝试过它。我会用聚合物试试。
猜你喜欢
  • 2011-06-24
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
相关资源
最近更新 更多