【问题标题】:How can I: Select a paragraph with JavaScript (on click)?我如何:使用 JavaScript 选择一个段落(点击时)?
【发布时间】:2014-10-16 19:30:00
【问题描述】:

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

(我是否需要使用 content-editable 才能使其工作?)

【问题讨论】:

标签: javascript jquery html dom textselection


【解决方案1】:

如果需要支持更高版本的浏览器,即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://stackoverflow.com/users/96100/tim-down 中的https://github.com/timdown/rangy

【讨论】:

  • 太棒了,太棒了,这不需要contenteditable。此外,包括代码 sn-p、规范参考、工作小提琴、指向更多信息的链接的主要道具! A+++答案
【解决方案2】:

select() 仅适用于 &lt;input&gt;&lt;textarea&gt; 元素...

也是的,你必须使用:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多