【问题标题】:detection of selected text not working properly检测所选文本无法正常工作
【发布时间】:2020-03-20 00:10:32
【问题描述】:

我正在尝试使用 javascript 检测 div 内的文本是否被选中,格式为 textarea。 HTML 是这样的:

<div id="rte-test" class="rich-text-editor">
    <ul class="toolbar">
        <li> <a href="#" class="command" id="...">...</a> </li>
    </ul>
    <div class="textarea" id="textareaContent" contentEditable="true"></div>
</div>

我试过这个 javascript 代码:

var command = document.getElementsByClassName("command");

for(var i=0; i<command.length; i++) {
  command[i].addEventListener("click", function() {
    var btn = this;
    var content = window.document.getElementById("textareaContent");
    if (content.getSelection) {
      console.log(content.getSelection() + ' selected. ' + btn.id);
    } else {
      console.log('nothing is selected. ' + btn.id);
    }
  });
}

使用此代码,即使在 textarea 上选择了某些内容,if/else 也只能达到“无选择”选项。

我也试过这个:

var command = document.getElementsByClassName("command");

for(var i=0; i<command.length; i++) {
  command[i].addEventListener("click", function() {
    var btn = this;
    if (window.getSelection) {
      console.log(window.getSelection() + ' selected. ' + btn.id);
    } else {
      console.log('nothing is selected. ' + btn.id);
    }
  });
}

使用此代码,即使未选择任何内容,if/else 也只能到达“已选择”选项。

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: javascript selection highlight


    【解决方案1】:

    试试

        if (window.getSelection().toString()) {
          console.log(window.getSelection() + ' selected. ' + btn.id);
        } else {
          console.log('nothing is selected. ' + btn.id);
        }
    

    window.getSelection() 返回一个非空对象,该对象始终为真,因为它非空。当您将window.getSelection() 放入console.log 时,会自动调用toString()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多