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

Ala*_* H. 4 javascript jquery html5 dom textselection

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

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

Jua*_*des 8

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

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

selection.removeAllRanges();
selection.addRange(range);
Run Code Online (Sandbox Code Playgroud)

相关链接:

有关所有浏览器的支持,请参阅https://github.com/timdown/rangy,网址/sf/users/6727031/