【问题标题】:Insert into textarea | JavaScript插入文本区域 | JavaScript
【发布时间】:2010-05-26 21:50:58
【问题描述】:

我正在尝试在编辑 textarea 值时将图像 url 插入到该点所在的位置。

function addImageURL()
{
 var imageurl = prompt("Enter image URL", "Your name")
 var post = document.getElementById("message-put").value;

 document.getElementById('message-put').value = post + '[img]' + imageurl + '[/img]';
}

这段代码抓取里面的值,在它旁边添加我不想要的图像 url,我需要它在编辑 textarea 时将它插入到点的位置

谢谢

编辑:

像 Stackoverflow 一样,您会看到图像图标,单击它或单击超链接,会出现一个框并将其插入到您正在编辑文本区域的位置:P

【问题讨论】:

  • ...编辑时的重点在哪里... O_o
  • 按点,你的意思是光标吗?
  • ...里面的值在旁边加上图片url... O_o 你的意思是要在光标处的文本区域插入一些东西吗?

标签: javascript dom textarea


【解决方案1】:

如果你想在光标处插入一些东西,这是我使用 Googlez 找到的:

function insertAtCaret(areaId, text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );

    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart('character', -txtarea.value.length);
        strPos = range.text.length;
    } else if (br == "ff") strPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0, strPos);
    var back = (txtarea.value).substring(strPos, txtarea.value.length);

    txtarea.value = front + text + back;
    strPos = strPos + text.length;

    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart('character', -txtarea.value.length);
        range.moveStart('character', strPos);
        range.moveEnd('character', 0);
        range.select();
    } 

    else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }

    txtarea.scrollTop = scrollPos;
}

来源:http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/(我没有测试过;它是 2008 年的,所以可能有点过时了)。

【讨论】:

    【解决方案2】:

    我在 WYSIWYG 中尝试实现类似功能时使用的一种技术:

    Retrieve parent node from selection (range) in Gecko and Webkit »StackOverflow

    如果使用框架,或者想避免我遇到的一些光标问题,可能会很有用。

    【讨论】:

      【解决方案3】:

      我想你可能会在这里找到你要找的东西:

      Caret position in textarea, in characters from the start

      这里有一个示例实现:

      http://javascript.nwbox.com/cursor_position/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-15
        • 2018-06-13
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        • 2011-08-06
        相关资源
        最近更新 更多