我有以下代码在HTML网页中显示一个文本框。

<input type="text" id="userid" name="userid" value="Please enter the user ID" />

当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。

是否可以只点击一下就选择整个文本?

编辑:

抱歉,我忘了说:我必须使用input type="text"


当前回答

你可以为HTMLElement使用JavaScript的.select()方法:

<label for="userid">用户ID <input onClick="this.select();" value="Please enter the user ID" ID ="userid" /> .

但显然它在移动版Safari上不起作用。在这些情况下,你可以使用:

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" id="userid" />

其他回答

像这样的Html <input type="text" value="点击输入选择" onclick="javascript:textSelector(this)" / >

和javascript代码没有绑定

function textSelector(ele){
    $(ele).select();
}

你可以为HTMLElement使用JavaScript的.select()方法:

<label for="userid">用户ID <input onClick="this.select();" value="Please enter the user ID" ID ="userid" /> .

但显然它在移动版Safari上不起作用。在这些情况下,你可以使用:

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" id="userid" />

你所问问题的确切解决方案是:

<input type="text" id="userid" name="userid" value="Please enter the user ID" onClick="this.setSelectionRange(0, this.value.length)"/>

但是我猜想,您试图在输入中显示“请输入用户ID”作为占位符或提示。 因此,您可以使用以下更有效的解决方案:

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />

下面是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触发时,你将失去合成事件。

实际上,可以使用onclick="this.select();",但记住不要将其与disabled="disabled"结合使用——这样就不能工作了,你仍然需要手动选择或多点点击来选择。如果希望锁定要选择的内容值,请结合属性readonly。