在 iframe 中使用替换方法的 Javascript

标签 javascript jquery html iframe replace

我想知道是否可以替换 iframe 中的某些单词。

我使用 jQuery 将 iframe 中的内容更改为相同的内容,但进行了替换。这里的问题是“光标重置”到输入字段的开头,因此您必须重新开始编写。

这就是我所做的

<html>
<head>
<script>
function iFrameOn(){
    richTextField.document.designMode = 'On';
}

</script>
</head>
<body onLoad="iFrameOn();">

<!-- Hide(but keep)your normal textarea and place in the iFrame replacement for it -->
<textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
<iframe name="richTextField" id="richTextField" style="border:#000000 1px solid; width:100px; height:20px;">
</iframe>
<!--End replacing your normal textarea -->
</p>
<script>
      function ReplaceWords(){
          var textfield = document.getElementById("richTextField");

          textfield.contentWindow.document.body.onkeyup = function(e){
              var content   = textfield.contentWindow.document.body.innerHTML;
              var Fixed_Content = content.replace("hey", "yo");
              $(document).ready(function() {
                  $('#richTextField').contents().find('body').html(Fixed_Content);
              });
          };
        };
      ReplaceWords();
</script>

</body>
</html>

问题是:是否可以在不重置光标的情况下替换 iframe 中的某些内容,因为它在您键入时不被欣赏并且它只是从头开始。

更新:基本上焦点不是文本区域,它隐藏在 iframe 中,因此我使用 document.designMode = 'On';

我又更新了帖子,从一开始就应该是这样的。

链接到 jsfiddle: https://jsfiddle.net/tqf3v2sk/8/

最佳答案

在同一域中使用 iFrame 与使用 DOM 元素没有太大区别。您只需确保在正确的 windowdocument 对象上调用您使用的方法。但是一旦您正确定位了窗口文档,您就可以从父窗口调用它们,就像它与您的脚本位于同一窗口中一样。

至于在您键入时进行替换,有几种方法可以做到。一种方法是使用 document.execCommand('insertText')Selection。您检测输入的键是否与要替换的单词的最后一个字符匹配,如果是,您选择要替换的单词的长度并检查它是否匹配。如果匹配,您调用 execCommand,它将替换它,将光标留在替换的末尾。

function replaceOnKeyDown(e, toReplace, replaceWith) {

  var iptFld = e.target;
  var lastLetter = toReplace[toReplace.length - 1];
  var keyEntered = String.fromCharCode(e.keyCode);
    console.log(keyEntered)
  // To make it more efficient, you can call the rest only if the
  // key just pressed is the same as the last of the word you
  // need to replace.
  if (lastLetter.toLowerCase() === keyEntered.toLowerCase()) {
    // Set selection to your word length
    var range = frameWindow.getSelection().getRangeAt(0);
    var caretPosition = range.startOffset;
    // Since you're on key down, the caret position is before the
    // last letter is entered.
    var toReplaceStart = caretPosition - toReplace.length + 1;

    range.setEnd(range.startContainer, caretPosition);
    range.setStart(range.startContainer, toReplaceStart);
    frameWindow.getSelection().addRange(range);
    // Check if the selection matches the word to replace
    // Since you're on mouse down, the range will only include 
    // up until the letter being entered. So you need to validate
    // that the word without the last letter equals
    // the selection.
    if (range.toString() + lastLetter === toReplace) {

      frameDocument.execCommand('insertText', false, replaceWith);
      // prevent last letter to be entered
      e.preventDefault();

    } else {

      frameWindow.getSelection().collapse(range.startContainer, caretPosition);

    }
  }
}

var textfield = document.getElementById("richTextField");
var frameWindow = textfield.contentWindow
var frameDocument = frameWindow.document
frameDocument.designMode = 'on'
frameDocument.body.onkeydown = function(e) {
  replaceOnKeyDown(e, 'hey', 'yo')
};

https://jsfiddle.net/k0qpmmw1/6/

关于在 iframe 中使用替换方法的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607401/

相关文章:

javascript - Datepickerfield 没有值可供选择 : Chrome

javascript - 如何使用 JavaScript 库使用椭圆曲线解密加密消息?

javascript - 在没有起始引用点的情况下如何获取父节点?

javascript - Convert JS function to jQuery - (输入字段清除默认值)

html - 已安装背景图片

javascript 隐藏/显示功能不起作用

javascript - 如何在 javascript 中访问对象的内容?

jquery - 防止多个 jQuery 动画同时发生

jquery - 如何从响应式设计中删除 slider

javascript - LinkedIn验证用户身份验证 token 服务器端