我正在尝试将输入文本从弹出窗口插入到页面上的文本区域(从光标位置定义)。
其想法是,用户单击按钮,将打开一个弹出窗口,用户可以在输入框中写入文本,然后单击按钮将该文本插入到光标所在位置的文本区域。
position = null;
function cursorPosition () {
if(!window.getSelection)
{
position = document.selection.createRange().duplicate();
}
else
{
position = window.getSelection();
}
}
function insertAtCaret (text)
{
position.text = text;
}
在弹出窗口中我有:
function onclose(text)
{
var newtext= text;
opener.insertAtCaret(newtext);
window.close();
}
无法使其在 Chrome 中运行,只能在 IE 中运行......每次我都会收到
Uncaught TypeError: Property 'insertAtCaret' of object [object Window] is not a function
有什么办法让它在所有浏览器中工作吗?
最佳答案
下面的代码接受来自输入框的输入,并根据需要将其添加到文本区域。它将输入框值附加到文本区域。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<textarea id="demo" cols="30" rows="5">
</textarea>
<script>
function myFunction()
{
var x;
var name=prompt("Please enter your name","Harry Potter");
if (name!=null)
{
x = document.getElementById("demo").value;
x = x + " Hello " + name + "! How are you today?"; // textarea value is appended here.
document.getElementById("demo").value=x;
}
}
</script>
</body>
</html>
关于javascript - 将弹出窗口中的文本插入文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14931934/