【问题标题】:Inserting text at cursor in a textarea, with Javascript使用Javascript在文本区域中的光标处插入文本
【发布时间】:2011-03-19 12:11:37
【问题描述】:

我在网上浏览了一些解决方案,有一些,但它们似乎都将代码拆分为支持 IE 和 Firefox。

我想知道是否有一种更优雅的方式适用于所有浏览器,在 textarea 的光标处插入一些文本。

非常感谢。

【问题讨论】:

    标签: javascript cross-browser textarea text-cursor


    【解决方案1】:

    不,没有。 IE 有它的TextRange 对象来完成这项工作。 IE >= 9 和其他所有东西在过去很长一段时间里都有 selectionStartselectionEnd 在文本区域和文本输入上的属性。这个特定的任务还不错:在所有主流浏览器中,以下将删除当前选择(如果存在),在插入符号处插入文本并在插入文本之后立即重新定位插入符号:

    function insertTextAtCursor(el, text) {
        var val = el.value, endIndex, range;
        if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
            endIndex = el.selectionEnd;
            el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
            el.selectionStart = el.selectionEnd = endIndex + text.length;
        } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
            el.focus();
            range = document.selection.createRange();
            range.collapse(false);
            range.text = text;
            range.select();
        }
    }
    

    【讨论】:

    • 非常感谢,我认为浏览器在过去几年中可能已经发展,但显然 IE 仍然选择不同。
    • 好消息是 IE 9 有 selectionStartselectionEnd
    • 这对我在所有三个浏览器中的实现都非常有用,我唯一遇到的问题是替换选定的文本。如果我将 val.slice(0, endIndex) 替换为 val.slice(0, startIndex) 它提供了突出显示选择并用添加的文本替换它的功能。仅适用于需要与我相同功能的其他人。
    • 如果您使用箭头移动光标,它不会按预期工作
    【解决方案2】:

    同时实现:支持 FF 的代码和支持 IE 的代码。您可以使用框架为两种浏览器编写代码。框架将完成拆分浏览器之间差异的工作。

    很遗憾,但浏览器并非 100% 兼容!

    【讨论】:

      猜你喜欢
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      相关资源
      最近更新 更多