【问题标题】:window.getSelection in ionic 3 / angular not working离子 3 / 角度中的 window.getSelection 不起作用
【发布时间】:2019-12-04 19:58:36
【问题描述】:

我正在尝试使用 window.getSelection 获取选定的文本。但它不起作用。我没有收到任何错误。

HTML

<span (mouseup)="showSelectedText()" id="descriptionText" class="val descriptionText" [innerHTML]="descriptionText"></span>

JS

showSelectedText(oField) {
  var text = "";
  if (window.getSelection) {
      text = window.getSelection().toString();
        console.log('text: ' + text)
  this.selectedText = text;
}

}

【问题讨论】:

    标签: angular ionic3


    【解决方案1】:

    找到了解决方法。也许有人正在寻找它。

    HTML

    <span #desc (mouseup)="pressEvent($event)" id="descriptionText" class="val descriptionText" [innerHTML]="descriptionText"></span>
    

    JS

    pressEvent(e) {
          var parentEl = null, sel;
          if (window.getSelection) {
            var s = window.getSelection();
              if (s && s.rangeCount > 0) {
                if (window.getSelection) {
                      if (s.rangeCount) {
                                parentEl = s.getRangeAt(0).commonAncestorContainer;
                                if (parentEl.nodeType != 1) {
                                    parentEl = parentEl.parentNode;
                                    }
                          }
                            }
                            else if ( (s = document.selection) && sel.type != "Control") {
                               parentEl = s.createRange().parentElement();
                            }
    
                          const p = JSON.stringify(parentEl);
                          const pt = JSON.parse(p);
                          if (pt.__zone_symbol__mouseupfalse) {
                                // start getSelectedWord
                                this.getSelectedWord(s);
                          }
              };
            }
      }
    
    
    getSelectedWord(s) {
        var range = s.getRangeAt(0);
        var node = s.anchorNode;
        while (range.toString().indexOf(' ') != 0) {
          range.setStart(node, (range.startOffset - 1));
        }
        range.setStart(node, range.startOffset + 1);
        do {
          range.setEnd(node, range.endOffset + 1);
    
        }
        while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
        var str = range.toString().trim();
        console.log(str)
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2019-06-11
      • 2021-02-10
      • 2018-05-08
      • 2018-06-20
      相关资源
      最近更新 更多