我有以下代码,允许我在用户每次单击时选择一个 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
已弃用 https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand我想改变它以获得一个好的替代方案。我怎样才能做到这一点?
总部设在阿尔瓦罗·蒂哈尼评论 https://stackoverflow.com/questions/59881237/alternative-for-document-execcommandselectall-false-null?noredirect=1#comment105891768_59881237 and 扭扭捏捏的评论 https://stackoverflow.com/questions/59881237/alternative-for-document-execcommandselectall-false-null/59881454?noredirect=1#comment105892061_59881454我发现了这个解决方案:
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)