How can I: Select a paragraph with JavaScript (on click)?

亡梦爱人 提交于 2019-12-10 16:16:23

问题


Is it possible to select all the text an an element (e.g., a paragraph <p>) with JavaScript? A lot of people think jQuery .select() would do this, but it does not. It merely triggers an event. Note that DOM objects for <input> elements have a native select() method, but most other elements (such as <output> and <p>) do not.

(Do I need to use content-editable to get this to work?)


回答1:


If you need to support later browsers, i.e., IE9+, you can use the following http://jsfiddle.net/q04jp0qx/2/

var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(document.getElementById('p'));

selection.removeAllRanges();
selection.addRange(range);

Related links:

  • The spec: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-Range-method-selectNodeContents
  • 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/Selection.addRange

For support across all browsers, see https://github.com/timdown/rangy from https://stackoverflow.com/users/96100/tim-down




回答2:


select() Will only work on <input> and <textarea> elements...

Also yes, you will have to use:

contenteditable="true"

And use .focus() to select all the text.

Try this:

<p id="editable" contenteditable="true" 
onfocus="document.execCommand('selectAll',false,null);">Your Text Here</p>

<button onclick="document.getElementById('editable').focus();" >Click me</button>

JSFiddle Demo



来源:https://stackoverflow.com/questions/25455567/how-can-i-select-a-paragraph-with-javascript-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!