javascript 我想将光标放在文本框的开头 onfocus
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8189384/
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
I want to put cursor in beginning of text-box onfocus
提问by Deepak Yadav
Possible Duplicate:
Set cursor at a length of 14 onfocus of a textbox
可能的重复:
将光标设置在文本框焦点上的 14 长度处
I am able to do that in firefox and IE. But for some reason its not working in Chrome and Safari :(
我可以在 Firefox 和 IE 中做到这一点。但由于某种原因它在 Chrome 和 Safari 中不起作用:(
I am simply using below line onfocus
我只是使用下面的线 onfocus
$('input:text').focus(
function(){
document.getElementById('id').setSelectionRange(0, 0);
});
Can someone please tell me how to do similar thing in Chrome and safari?
有人可以告诉我如何在 Chrome 和 safari 中做类似的事情吗?
回答by Tim Down
The problem is that Chrome (I haven't heard of Safari doing this as well, but I'll take you word for it) kills the selection after the focus event has fired, so you need to add a timer. The following is adapted from my answer here:
问题是 Chrome(我还没有听说 Safari 也这样做,但我会相信你的话)在焦点事件触发后杀死选择,所以你需要添加一个计时器。以下内容改编自我在这里的回答:
How to place cursor at end of text in textarea when tabbed into
However, this generally isn't good usability: it's contrary to what the user expects and removes useful functionality when using the mouse (i.e. the caret going to the location the user clicks). You can probably get around that with some handling of mousedown
and mouseup
events.
然而,这通常不是很好的可用性:它与用户的期望相反,并在使用鼠标时删除了有用的功能(即插入符号转到用户单击的位置)。您可能可以通过一些处理mousedown
和mouseup
事件来解决这个问题。
Live demo: http://jsfiddle.net/timdown/z9DhX/1/
现场演示:http: //jsfiddle.net/timdown/z9DhX/1/
Code:
代码:
function moveCaretToStart(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = 0;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(true);
range.select();
}
}
var textBox = document.getElementById("id");
textBox.onfocus = function() {
moveCaretToStart(textBox);
// Work around Chrome's little problem
window.setTimeout(function() {
moveCaretToStart(textBox);
}, 1);
};
回答by gilly3
Webkit is resetting the caret position as part of the focus event. You need to defer execution of your script until after the event has fully fired. Using setTimeout
with a delay of 0
is good enough:
Webkit 正在重置插入符号位置作为焦点事件的一部分。您需要将脚本的执行推迟到事件完全触发之后。setTimeout
延迟使用0
就足够了:
$(":text").focus(function () {
var input = this;
setTimeout(function() {
input.setSelectionRange(0, 0);
}, 0);
});
Working demo: http://jsfiddle.net/ZkqGH/1/
工作演示:http: //jsfiddle.net/ZkqGH/1/