【问题标题】:Trigger selection of contenteditable触发内容可编辑的选择
【发布时间】:2023-03-17 09:53:02
【问题描述】:

为什么这不会选择(即以蓝色突出显示等)内容可编辑的<div>

注意:我使用的是 Firefox 36.0.1 (Windows 7)

$('#b').click(function() { $('#a').select().focus(); } );
<div id="a" contenteditable>Hello</div>
<div id="b">click here</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

【问题讨论】:

  • 似乎对我有用。你用的是什么浏览器?
  • @putvande firefox 36.0.1
  • @Basj -- 你有没有尝试实际输入一些东西? contenteditable 是 html5 - 您的浏览器可能太旧而无法支持它(我有 FF 44 并且工作正常)
  • 但是this 建议它应该可以在您的浏览器上正常工作

标签: javascript jquery contenteditable


【解决方案1】:

正如here 所建议的那样,至少在 Firefox 中有效:

$('#b').click(function() { $('#a').select().focus(); document.execCommand('selectAll', false, null); } );
<div id="a" contenteditable>Hello</div>
<div id="b">click here</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

【讨论】:

    【解决方案2】:

    select() 函数不适用于 contenteditable 元素。看@ https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

    HTMLInputElement.select() 方法选择 元素或带有文本的 元素中的所有文本字段。

    您可以设置范围来选择文本或部分文本。 要选择 contenteditable 文本,您可以使用:

    function selectAll() {
      var editor = document.getElementById('a');
      var selection = document.getSelection();
      selection.removeAllRanges();
      var range = document.createRange();
      range.selectNodeContents(editor);
      selection.addRange(range);
    }
    

    http://codepen.io/anon/pen/QNPGxW

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      相关资源
      最近更新 更多