是否可以选择一个元素的所有文本(例如,一个段落)<p>
)与 JavaScript?很多人认为 jQuery.select()
会这样做,但事实并非如此。它只是触发一个事件。请注意,DOM 对象<input>
元素有一个原生的select()
方法,但大多数其他元素(例如<output>
and <p>
) 不要。
(我需要使用content-editable
让它发挥作用?)
您可以使用Range.selectNodeContents 范围.selectNodeContents https://developer.mozilla.org/en-US/docs/Web/API/Range/selectNodeContents
document.querySelector('button').addEventListener('click', function(){
var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(document.querySelector('p'));
selection.removeAllRanges();
selection.addRange(range);
});
Hello <p>Select me</p> World
<button id ='btn'>Select text</button>
相关链接:
- 规格:http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-Range-method-selectNodeContents http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-Range-method-selectNodeContents
- http://help.dottoro.com/ljcpcpnt.php http://help.dottoro.com/ljcpcpnt.php
- https://developer.mozilla.org/en-US/docs/Web/API/range.selectNodeContents https://developer.mozilla.org/en-US/docs/Web/API/range.selectNodeContents
- https://developer.mozilla.org/en-US/docs/Web/API/Selection.addRange https://developer.mozilla.org/en-US/docs/Web/API/Selection.addRange
有关所有浏览器的支持,请参阅https://github.com/timdown/rangy https://github.com/timdown/rangy from https://stackoverflow.com/users/96100/tim-down https://stackoverflow.com/users/96100/tim-down
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)