javascript 如何聚焦输入,并取消选择其中的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11404130/
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
How to focus input, and deselect text inside it
提问by Solo
I am currently wanting to focus the first input element, without selecting the preset value text inside the input element. How can I focus my input element, and then deselect the text inside it? My current focus jQuery is as follows.
我目前想要聚焦第一个输入元素,而不选择输入元素内的预设值文本。如何聚焦我的输入元素,然后取消选择其中的文本?我目前的重点 jQuery 如下。
$(document).ready(function() {
$("input[name='title']").focus();
});
采纳答案by Chief120
$(document).ready(function() {
$("input[name='title']").focus();
$("input[name='title']").val($("input[name='title']").val());
});
回答by Danilo Valente
You can use the selectionStart
and selectionEnd
properties:
您可以使用selectionStart
和selectionEnd
属性:
$(document).ready(function() {
$("input[name='title']").each(function(){
this.focus();
this.selectionEnd = this.selectionStart;
});
});
回答by rangfu
This is based on Danilo Valente's answer above. I found that on Chrome I had to use a tiny delay before calling this.selectionEnd = this.selectionStart
, otherwise the input text would remain selected:
这是基于 Danilo Valente 上面的回答。我发现在 Chrome 上我必须在调用之前使用一个很小的延迟this.selectionEnd = this.selectionStart
,否则输入文本将保持选中状态:
This works for me on Chrome, Firefox, Safari and IE (tested IE 10)
这适用于我在 Chrome、Firefox、Safari 和 IE 上(经过 IE 10 测试)
$("input").focus(function() {
var input = this;
setTimeout(function() { input.selectionStart = input.selectionEnd; }, 1);
});
Here's a demo: http://jsfiddle.net/rangfu/300ah0ax/2/
回答by Leniel Maccaferri
$("input[name='title']").focus(function()
{
var elem = $(this);
elem.val(elem.val());
});