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

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

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

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

编辑:

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


当前回答

当.select()在移动平台上不起作用时,这个问题有选项:在iOS设备(移动Safari)上以编程方式选择输入字段中的文本

其他回答

我认为通过事件来控制更好。这个变体看起来很直观,也适用于ts:

    onFocus={e => {
      e.target.select();
    }

如果你每次点击都需要selectAll,你可以使用这个:

    onClick={e => {
      e.target.focus();
      e.target.select();
    }

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

和javascript代码没有绑定

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

Try:

onclick="this.select()"

这对我来说很有效。

下面是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(你必须把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>