[英]How can I: Select a paragraph with JavaScript (on click)?
是否可以使用 JavaScript 選擇所有文本和 an 元素(例如,段落<p>
)? 很多人認為 jQuery .select()
會做到這一點,但事實並非如此。 它只是觸發一個事件。 請注意, <input>
元素的 DOM 對象具有本機select()
方法,但大多數其他元素(例如<output>
和<p>
)沒有。
(我需要使用content-editable
來讓它工作嗎?)
如果需要支持更高版本的瀏覽器,即IE9+,可以使用以下
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>
相關鏈接:
有關所有瀏覽器的支持,請參閱https://github.com/timdown/rangy從https://stackoverflow.com/users/96100/tim-down
select()
僅適用於<input>
和<textarea>
元素...
也是的,您必須使用:
contenteditable="true"
並使用.focus()
選擇所有文本。
嘗試這個:
<p id="editable" contenteditable="true"
onfocus="document.execCommand('selectAll',false,null);">Your Text Here</p>
<button onclick="document.getElementById('editable').focus();" >Click me</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.