我有以下代码在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"
当前回答
下面是React中的一个例子,但如果你喜欢,它可以在香草JS上翻译成jQuery:
class Num extends React.Component {
click = ev => {
const el = ev.currentTarget;
if(document.activeElement !== el) {
setTimeout(() => {
el.select();
}, 0);
}
}
render() {
return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
}
}
这里的技巧是使用onMouseDown,因为元素在“click”事件触发时已经收到了焦点(因此activeElement检查将失败)。
activeElement检查是必要的,这样用户就可以将光标定位到他们想要的位置,而不必不断地重新选择整个输入。
超时是必要的,因为否则文本将被选中,然后立即取消选中,因为我猜浏览器在后面会进行光标定位检查。
最后,el = ev。currentTarget在React中是必要的,因为React重用事件对象,当setTimeout触发时,你将失去合成事件。
其他回答
像这样的Html <input type="text" value="点击输入选择" onclick="javascript:textSelector(this)" / >
和javascript代码没有绑定
function textSelector(ele){
$(ele).select();
}
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>
以下是Shoban回答的可重复使用版本:
<input type="text" id="userid" name="userid"
value="Please enter the user ID" onfocus="Clear(this);"
/>
function Clear(elem)
{
elem.value='';
}
这样就可以为多个元素重用clear脚本。
Try:
onclick="this.select()"
这对我来说很有效。
我正在寻找一个css唯一的解决方案,发现这适用于iOS浏览器(测试safari和chrome)。
它在桌面chrome上没有相同的行为,但选择的痛苦没有那么大,因为作为用户,你有更多的选项(双击,ctrl-a等):
.select-all-on-touch {
-webkit-user-select: all;
user-select: all;
}