window.getSelection不起作用在IE11中不起作用

window.getSelection not working is not working in IE11

本文关键字:不起作用 IE11 window getSelection      更新时间:2023-09-26

我们开始在IE11中测试我们的应用程序,并注意到window.getSelection()在IE11中没有得到选择。我没有看到IE11不支持此属性的任何位置,并且根据我的理解window.getSelection应该适用于9的所有IE版本。

还有其他人遇到过这个问题吗?我在这里错过了什么吗?

我创建了以下示例,该示例可以在旧版本的IE和Chrome中按预期工作,但在IE11中则不然。

$('#selectButton').on('click', function() {
    $('#name').select();
    var sel = window.getSelection();
    alert("Slected value in text area : " + sel);
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='selectAll' id='selectAll'>
  <textarea id='name' name='name'>Sample Value</textarea>
  <br>
  <input type='button' value='Click Me' id='selectButton' />
</form>

更新 - 经过进一步调查,我已经发现 window.getSelection() 确实存在于 IE 11 中,但当所选文本位于文本区域等输入字段中时,它将无法正常工作。我也知道FF曾经有一个类似的错误。在这一点上,我不确定这是IE中的错误还是预期的行为。

您没有获得所选内容中的文本,因为您没有选择任何内容。

textarea等交互式元素具有自己的选择模型,getSelection方法都不能用于从这些元素中获取选择。这也代表火狐。

要在IE和FF中解决此问题,请使用HTMLInputElement API:

$('#selectButton').on('click', function() {
    var area = $('#name')[0],
        sel;
    area.select();
    sel = area.value.substring(
    	area.selectionStart,
        area.selectionEnd
    );
    alert("Selected value in text area : " + sel);
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='selectAll' id='selectAll'>
  <textarea id='name' name='name'>Sample Value</textarea>
  <br>
  <input type='button' value='Click Me' id='selectButton' />
</form>

此外,在FF中,内容可编辑元素也可以部分使用HTMLInputElement API,但不仅限于它。

我相信

答案就在页面上 https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

在该页面上的"浏览器兼容性"部分中,仅列出了 Internet Explorer 版本 9。 根据 Mozilla 网站上的其他页面,如果所有版本的 IE 都支持它,它将在 Internet Explorer 浏览器兼容性下列出"是"。

这似乎是IE 11的问题。根据 MS,这在他们的新浏览器"Microsoft Edge"中已修复,但在 IE 11 中不会修复。

微软错误链接