选择一个JavaScript段落(点击)
Select a paragraph with JavaScript (on click)?
是否可以选择一个元素的所有文本(例如,段落<p>
)与JavaScript?很多人认为jQuery .select()
会做到这一点,但它没有。它只是触发一个事件。注意,<input>
元素的DOM对象有一个原生的select()
方法,但大多数其他元素(如<output>
和<p>
)没有。
(我需要使用content-editable
来让这个工作吗?)
可以使用Range.selectNodeContents
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>
相关链接:
- 规格: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
有关跨所有浏览器的支持,请参阅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>
<<p> JSFiddle演示/strong> 相关文章:
- 分派点击事件并保留击键修饰符
- JavaScript下拉菜单-点击按钮并根据所选值重定向到url
- jquery点击函数select&取消选择
- ExtJS 5用程序点击actioncolumn gridview
- 我可以获得相对于被点击元素的确切点击位置吗
- 如何在Bootstrap Modal中为动态点击生成的变量设置jade属性
- 对iPad上的点击事件反应缓慢
- 剑道UI内联编辑:如何在点击其他按钮时隐藏按钮
- 我应该使用Ng提交还是点击表格
- 手风琴可点击并悬停
- python-selenium-点击上升链接
- Javascript html每点击一次就会更改url
- 当我点击jsf中的primefaces命令按钮时,如何获得点击事件
- 点击按钮输入不起作用
- 火狐:三次点击的段落选择会产生我所期望的行为
- jQuery点击事件前的段落标记两次
- 选择一个JavaScript段落(点击)
- 如何使链接在点击时改变段落的内容?返回false,不工作
- 如何隐藏段落和使可见的标题点击使用Javascript
- 如何一次显示一个段落的一个新单词,通过按键或鼠标点击移动