检测到所选文本无法正常工作

detection of selected text not working properly

我正在尝试使用 javascript 检测是否选择了格式为 textareadiv 中的文本。 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 也只能达到 "nothing is select" 选项。

我也试过这个:

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 也只能到达 "selected" 选项。

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

尝试

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

window.getSelection() returns 一个非空对象,它永远为真,因为它不为空。当您将 window.getSelection() 放入 console.log 时,会自动调用 toString()