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