Gui*_*Vaz 19 html javascript jquery google-chrome
我正在尝试将光标设置在具有焦点功能的文本字段中.我做了一些研究,但提供的解决方案似乎都不适用于谷歌浏览器.在Internet Explorer和Firefox中,此解决方案正常运行:
js:
$('#Search').focus(function() {
var SearchInput = $('#Search');
var strLength= SearchInput.val().length;
SearchInput.focus();
SearchInput[0].setSelectionRange(strLength, strLength);
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<input type="text" id="Search" value="Hello World" />
Run Code Online (Sandbox Code Playgroud)
这是我的jsfiddle的链接.
有没有什么方法可以在谷歌浏览器中使用它?
ruu*_*ska 19
在聚焦输入时放置光标之前似乎焦点事件被触发,一个hacky解决方法是使用setTimeout,如下所示:
$('#Search').focus(function() {
setTimeout((function(el) {
var strLength = el.value.length;
return function() {
if(el.setSelectionRange !== undefined) {
el.setSelectionRange(strLength, strLength);
} else {
$(el).val(el.value);
}
}}(this)), 0);
});
Run Code Online (Sandbox Code Playgroud)
试试这个小提琴: http ://jsfiddle.net/esnvh/26/
编辑为0ms超时,因为@SparK指出这足以推送到执行队列的末尾.
更新的代码
参考:http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
setSelectionRange IE,Opera和Safari 不支持
我建议你做这样的事情(适用于IE,Chrome,Safari,Firefox).
$('#Search').on('mouseup', function() {
var element = $(this)[0];
if (this.setSelectionRange) {
var len = $(this).val().length * 2;
element.setSelectionRange(len, len);
}
else {
$(this).val($(this).val());
$(this).focus();
}
element.scrollTop = 9999;
});
Run Code Online (Sandbox Code Playgroud)
试试这个:http://jsfiddle.net/r5UVW/4/
| 归档时间: |
|
| 查看次数: |
41477 次 |
| 最近记录: |