javascript - 使用 JavaScript 将光标置于 iframe 正文元素中的文本末尾

标签 javascript html iframe

首先我要道歉,因为这可能看起来或实际上是重复的,但我已经尝试了遇到的所有解决方案,但似乎没有一个对我有用。

在我的 HTML 中,我有一个引用另一个 HTML 文档的 iframe。使用 JavaScript,按下一系列按钮后,我将文本插入该 iframe 的正文中。我还使用 JavaScript 来保持对 iframe 主体的关注。问题是,每次我按下这些按钮时,似乎没有任何东西可以让光标移动到文本的末尾,它总是移动到开头。

我尝试过的解决方案之一是将此代码添加到处理按钮按下的函数中:

iFrameBody.focus();
var content = iFrameBody.innerHTML;
iFrameBody.innerHTML = content;

所以函数看起来像这样:

function typeIn(buttonId) {

    var iFrameBody = document.getElementById("iFrame").contentWindow.document.body;
    iFrameBody.innerHTML += buttonId;

    iFrameBody.focus();
    var content = iFrameBody.innerHTML;
    iFrameBody.innerHTML = content;
}

我尝试过的其他事情是,在我的 iframe 引用的 HTML 文件中,我做了:

<body onfocus="this.innerHTML = this.innerHTML;"></body>

我尝试了其他几个更复杂的解决方案,坦白说我什至不太明白,但都无济于事。任何帮助将不胜感激。

最佳答案

我明白了。问题是我正在使用 body 元素,写入它的 innerHTML 并尝试将焦点设置在 body 上。通过简单地在我的 iFrame 中使用文本区域,它变得非常简单,并且只需要最简单的代码。

这可以在页面加载时设置焦点:

window.onload = function () {

    var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameTextArea");
    iFrameTextArea.focus();
}

然后将按钮设置为在保持焦点的同时写入文本区域:

function typeIn(buttonId) {

    var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameInput");

    iFrameTextArea.focus();

    iFrameTextArea.value += buttonId;

}

super 简单!!

关于javascript - 使用 JavaScript 将光标置于 iframe 正文元素中的文本末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33906334/

相关文章:

javascript - 触摸事件后移动 div

javascript - 我想将基数 10 的数字更改为基数 16

javascript - 如何创建一个 Angular 分量的独立实例

html - 在 IFrame 中显示 PDF 时处理错误消息

.htaccess - 如何阻止iframe通话

javascript - HTML,将 iframe src 设置为 JavaScript 变量

javascript - 如何让 JavaScript 代码更防弹?

javascript - 如何从ajax获取发送响应到脚本

html - Razor - 从数组中应用随机 CSS 类

javascript - 使用pubnub和webrtc在canvas之间成功传输数据