javascript 获得焦点时选择“只读” <input /> 中的所有文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13887430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select all text in a 'readonly' <input /> when it gains focus
提问by CBarr
I've got a textbox (set to readonly) and I need its' contents to be selected for easy copy/paste when it gains focus. Using the code below it only seems to quickly select the text and then unselect it for some reason.
我有一个文本框(设置为只读),我需要选择它的内容,以便在获得焦点时轻松复制/粘贴。使用下面的代码似乎只能快速选择文本,然后出于某种原因取消选择它。
HTML
HTML
<input id='thing' type='text' value='some text' readonly='readonly' />?
JavaScript
JavaScript
document.getElementById('thing').onfocus = function(){
this.select();
};?
Fiddle: http://jsfiddle.net/cfqje/
回答by JNK
This seems to be a work around:
这似乎是一种解决方法:
<input id='thing' type='text' value='some text' onclick="this.select()" readonly='readonly' />?
I guess the problem is that focus doesn't work correctly as the input is readonly.
我想问题是焦点无法正常工作,因为输入是只读的。
回答by Frank L?mmer
You can now use CSS. With user-select: all;
all text will be selected when a clicking on an element.
您现在可以使用 CSS。随着user-select: all;
所有文本将被选中,当点击一个元素。