我有以下代码在HTML网页中显示一个文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。
是否可以只点击一下就选择整个文本?
编辑:
抱歉,我忘了说:我必须使用input type="text"
我有以下代码在HTML网页中显示一个文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。
是否可以只点击一下就选择整个文本?
编辑:
抱歉,我忘了说:我必须使用input type="text"
当前回答
Html(你必须把onclick属性放在你想要它在页面上工作的每个输入上)
<input type="text" value="click the input to select" onclick="this.select();"/>
或者一个更好的选择
jQuery(这将适用于页面上的每个文本输入,不需要改变你的html):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click','input[type=text]',function(){ this.select(); });
});
</script>
其他回答
我在vue应用程序中使用焦点属性
<input @focus="$event.target.select()" />
我正在寻找一个css唯一的解决方案,发现这适用于iOS浏览器(测试safari和chrome)。
它在桌面chrome上没有相同的行为,但选择的痛苦没有那么大,因为作为用户,你有更多的选项(双击,ctrl-a等):
.select-all-on-touch {
-webkit-user-select: all;
user-select: all;
}
在输入字段中使用“占位符”而不是“值”。
以下是Shoban回答的可重复使用版本:
<input type="text" id="userid" name="userid"
value="Please enter the user ID" onfocus="Clear(this);"
/>
function Clear(elem)
{
elem.value='';
}
这样就可以为多个元素重用clear脚本。
注意:当你考虑onclick="this.select()"时,在第一次点击时,所有字符都会被选中,之后可能你想在输入中编辑一些东西,然后再次点击字符,但它会再次选中所有字符。要解决这个问题,你应该使用onfocus而不是onclick。