2010-05-26 57 views
1

我试图在编辑textarea值时插入图像的地址点。插入到textarea | JavaScript

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旁边,我不想,我需要它插入点在哪里编辑文本区域时被

感谢

编辑:

像#1,你看到的图片图标,单击或点击超链接,一个盒子里并插入它,你正在编辑的文本域:P

alt text http://i45.tinypic.com/eqa7m8.png

+0

...其中点的编辑时... O_o – 2010-05-26 21:52:45

+0

点,你的意思是光标? – 2010-05-26 21:53:04

+2

...内部的值将图像的网址添加到它旁边... O_o 您的意思是您想要在光标的文本区域插入某些内容吗? – 2010-05-26 21:53:47

回答

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年开始,所以可能会有点过时)。