我该怎么做:用JavaScript选择一个段落(点击)?

时间:2014-08-22 21:10:11

标签: javascript jquery html5 dom textselection

是否可以使用JavaScript选择所有文本作为元素(例如,段落<p>)?很多人认为jQuery .select()会这样做,但事实并非如此。它只是触发一个事件。请注意,<input>元素的DOM对象具有原生select()方法,但大多数其他元素(例如<output><p>)则没有。

(我需要使用content-editable才能使其正常工作吗?)

2 个答案:

答案 0 :(得分:6)

如果您需要支持以后的浏览器,即IE9 +,您可以使用以下http://jsfiddle.net/q04jp0qx/2/

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

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

相关链接:

要获得所有浏览器的支持,请参阅https://github.com/timdown/rangy

中的https://stackoverflow.com/users/96100/tim-down

答案 1 :(得分:3)

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>

<强> JSFiddle Demo

相关问题