【问题标题】:Alternative for document.execCommand('selectAll',false,null) [duplicate]替代 document.execCommand('selectAll',false,null) [重复]
【发布时间】:2020-05-09 21:11:57
【问题描述】:

我有以下代码,允许我在每次用户点击时选择一个 div 文本:

<table>
  <tr>
    <td>
      <div contenteditable onClick="document.execCommand('selectAll',false,null)">I'm editable</div>
    </td>
  </tr>
  <tr>
    <td>
      <div contenteditable>I'm also editable</div>
    </td>
  </tr>
  <tr>
    <td>I'm not editable</td>
  </tr>
</table>

我的问题是 document.execCommand is deprecated 我想将其更改为一个好的替代方案。我该怎么做?

【问题讨论】:

标签: javascript html css


【解决方案1】:

基于Alvaro Tihanyi commentShilly comment 我找到了这个解决方案:

function selectText(element) {
    if (document.selection) { // IE
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(element);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<table>
  <tr>
    <td>
      <div id="selectable" contenteditable onclick="selectText(this)">I'm editable</div>
    </td>
  </tr>
  <tr>
    <td>
      <div contenteditable>I'm also editable</div>
    </td>
  </tr>
  <tr>
    <td>I'm not editable</td>
  </tr>
</table>

【讨论】:

  • 使用实际的事件监听器,这样您就可以使用event.target 来引用 div,而不是 HTML 中传递字符串以用作选择器的内联事件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多