本文介绍了如何在Google Chrome输入文字末尾设置光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图在具有焦点功能的文本字段中设置光标。我做了一些研究,但所提供的解决方案似乎都不适用于Google Chrome。在Internet Explorer和Firefox中,这个解决方案工作正常: js: var SearchInput = $('#Search'); var strLength = SearchInput.val()。length; SearchInput.focus(); SearchInput [0] .setSelectionRange(strLength,strLength); }); HTML: < input type =textid =Searchvalue =Hello World/> 以下是我的 jsfiddle 。 有什么方法可以在谷歌浏览器中使用它? $ b 解决方案 $('#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); }); 试试这个小提琴: http://jsfiddle.net/esnvh/26/ 编辑为0ms超时,因为@SparK指出这足以推动执行队列的结束。 I'm trying to set the cursor in a text field with a focus function. I've made some research but none of the provided solutions seemed to work in Google Chrome. In Internet Explorer and Firefox this solution is working fine: The js:$('#Search').focus(function() { var SearchInput = $('#Search'); var strLength= SearchInput.val().length; SearchInput.focus(); SearchInput[0].setSelectionRange(strLength, strLength);});The HTML:<input type="text" id="Search" value="Hello World" />Here's the link to my jsfiddle.Is there any way to make this work in Google Chrome too? 解决方案 It seems like the focus event is fired before the cursor is placed when you focus an input, a hacky workaround would be to use a setTimeout like so:$('#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);});Try this fiddle: http://jsfiddle.net/esnvh/26/Edited to 0ms timeout, as @SparK pointed out this is enough to push to end of execution queue. 这篇关于如何在Google Chrome输入文字末尾设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-25 02:57