我们开始在 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
方法不能用于从这些元素中获取选择。这也代表 Firefox。
要在 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,但不仅限于此。
关于javascript - window.getSelection 不工作在 IE11 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35162273/