如何在Javascript中将光标移动到textarea的最后位置? [英] How can you move the cursor to the last position of a textarea in Javascript?

查看:721
本文介绍了如何在Javascript中将光标移动到textarea的最后位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单上有一个textarea和一个按钮。 textarea可能已经有一些文本。我希望当单击按钮时光标移动到文本区域的最后位置。

I have a textarea and a button on a form. The textarea may already have some text in it. I would like the cursor to move to the last position in the text area when the button is clicked.

这可能吗?

推荐答案

通过最后一个位置,您的意思是文本的结尾吗?

更改表单字段的'.value'会将光标移动到除IE之外的每个浏览器的末尾。使用IE,你必须弄脏并故意操纵选择,使用非标准接口:

Changing the ‘.value’ of a form field will move the cursor to the end in every browser except IE. With IE you have to get your hands dirty and deliberately manipulate the selection, using non-standard interfaces:

    if (browserIsIE) {
        var range= element.createTextRange();
        range.collapse(false);
        range.select();
    } else {
        element.focus();
        var v= element.value();
        element.value= '';
        element.value= v;
    }

或者你的意思是把光标放回原来的位置以前,textarea最后一次聚焦了吗?

在IE以外的每个浏览器中,只需调用'element.focus()'即可;浏览器会记住每个输入的最后一个光标/选择位置并将其重新置于焦点上。

In every browser except IE, this will already happen just by calling ‘element.focus()’; the browser remembers the last cursor/selection position per input and puts it back on focus.

在IE中重现这将非常棘手。您必须始终轮询以检查光标/选择的位置,并记住该位置(如果它位于输入元素中),然后在按下按钮时获取给定元素的位置并将其恢复。这涉及到'document.selection.createRange()'的一些非常繁琐的操作。

This would be quite tricky to reproduce in IE. You would have to poll all the time to check where the cursor/selection was, and remember that position if it was in an input element, then fetch the position for a given element when the button was pressed and restore it. This involves some really quite tedious manipulation of ‘document.selection.createRange()’.

我不知道jQuery中有什么可以帮助你做到这一点,但是也许某个地方可能有插件?

I'm not aware of anything in jQuery that would help you do this, but there might be a plugin somewhere perhaps?

这篇关于如何在Javascript中将光标移动到textarea的最后位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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