文本区接收输入的URL值,并在文本区显示URL,不带代码(<a href=..)

text area recieve input value which URL and display the URL in text area without code (<a href=....)

本文关键字:文本区 URL 代码 href 显示 输入      更新时间:2023-09-26

我有下面的代码,从当前光标位置的不同输入字段插入值到文本区域。文本区域接收URL输入。文本区成功地接收了输入,但它以编码的形式出现。我想让它成为一个可点击的链接。这可能吗?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Page</title>
<script type="text/javascript">
window.onload = function()
{
        btn = document.getElementById("btnInsertText");
        myText = document.getElementById("myTextArea");
        title = document.getElementById("insTitle");
        url = document.getElementById("insUrl");
        btn.onclick = function()
        {
            insertAtCursor(myText, title.value, url.value);
        }
}
function insertAtCursor(myField, title, url)
{ 
    //IE support 
    if (document.selection)
    { 
        myField.focus();
        sel = document.selection.createRange(); 
        sel.text = '<a href="'+url+'">'+title+'</a>'; 
    }
    //Mozilla/Firefox/Netscape 7+ support 
    else if (myField.selectionStart || myField.selectionStart == '0')
    {  
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd; 
        myField.value = myField.value.substring(0, startPos)+ '<a href="'+url+'">'+title+'</a>' + myField.value.substring(endPos, myField.value.length);
    }
    else
    { 
        myField.value += myValue; 
    } 
}       
</script>
</head>
<body>
  title: <input type="text" id="insTitle" /><br />
  url: <input type="text" id="insUrl" />
  <input type="button" id="btnInsertText" value="Insert Text" /><br /><br />
  <textarea id="myTextArea" rows="6" cols="50">
    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
  </textarea>
</body>
</html>

这是不可能的,除非你通过CSS将链接放置在文本区域上。