chrome setSelectionRange()在oninput处理程序中不工作 [英] chrome setSelectionRange() not work in oninput handler

查看:620
本文介绍了chrome setSelectionRange()在oninput处理程序中不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些自动完成代码。 setSelectionRange()用于在 oninput 事件处理程序中选择已完成的文本。

I'm working with some auto-completion code. setSelectionRange() is used to select text been completed in oninput event handler. It works at least in Firefox 14, but not in Chrome(6, 17).

简化的代码片段演示的问题是这样的:

Simplified code snippet demonstrating the problem is like this:

<input type='text' oninput='select()' />



function select(e){
    var s = this.value;
    if (s.length)
        this.setSelectionRange(s.length-1, s.length);
}

我在Chrome中调试了代码,

I debugged the code in chrome, and it turns out that text has been selected at first right after the setSelectionRange() been executed, but the selection disappeared later.

如果我绑定了处理程序,那么在第一次执行 setSelectionRange() onclick 而不是 oninput ,例如:

If i bind the handler to onclick instead of oninput, like this:

<input type='text' onclick='select()' />

这两种浏览器都可以正常工作。

then both browsers work fine.

任何人都可以给我一些线索,使选择工作在Chrome?

Can anyone please give me some clue to make selection work in Chrome?

推荐答案

您的代码有一些问题,传递到 select()函数中的参数都是错误的:这个将会是 c $ c>和 e 将是未定义的。此外,在 oninput 属性中使用 select()作为函数名会导致一个问题,因为select将解析为 select()方法的输入本身。更好的方法通常是在脚本中设置事件处理程序,而不是通过事件处理程序属性。

There are some problems with your code, namely that the parameters passed into the select() function are wrong: this will be window and e will be undefined. Also, using select() as a function name within the oninput attributes causes a problem because select will resolve to the select() method of the input itself. A better approach is usually to set the event handler in script rather than via an event handler attribute.

但是,即使纠正这些问题后,问题仍然存在。可能在浏览器在Chrome中移动插入符号之前触发输入事件。一个简单的解决方法是使用一个计时器,虽然这是次优的,因为有可能用户将能够在计时器触发之前输入另一个字符。

However, the problem exists even after correcting these issues. Possibly the input event fires before the browser has moved the caret in Chrome. A simple workaround would be to use a timer, although this is sub-optimal because there's a possibility the user will be able to input another character before the timer fires.

演示: http://jsfiddle.net/XXx5r/2/

代码:

<input type="text" oninput="selectText(this)">

<script type="text/javascript">
function selectText(input) {
    var s = input.value;
    if (s.length) {
        window.setTimeout(function() {
            input.setSelectionRange(s.length-1, s.length);
        }, 0);
    }
}
</script>

这篇关于chrome setSelectionRange()在oninput处理程序中不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆