【问题标题】:Javascript using replace method inside an iframe在 iframe 中使用替换方法的 Javascript
【发布时间】:2016-04-09 00:35:53
【问题描述】:

我想知道是否可以替换 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/

【问题讨论】:

  • 你有一个额外的;。在定义它之前调用Hello()。您可以使用onmouseenter 事件或设置时间间隔来执行此操作。展示一个例子会很棒。
  • 谢谢,但是在 mouseenter 上它不会是实时的,而写作。
  • 如果我在 iframe 中理解你的意思,你会加载输入字段,当用户键入时,你会尝试替换输入文本的某些部分。如果是,那么您可以将输入字段值替换为更新的值,而不是替换 html 标签。因为所描述问题的整个文档替换原因。否则,如果标签替换正是您所需要的,您可以在内容更改后在输入字段上调用焦点方法。
  • 如果我理解正确,您有一些 input/textarea/contenteditable 元素并想要修改其内容,但保持光标位置(如果光标位于被替换部分会发生什么?)。这可能与Stop cursor from jumping to end of input field in javascript replace 重复。 iframe 似乎是多余的。
  • 正如@Oriol 提到的,iframe 似乎是多余的。我认为如果你能提供一个工作小提琴会更好(通过 jsfiddle 或 codepen 等网站)

标签: javascript jquery html iframe replace


【解决方案1】:

在同一域中使用 iFrames 与使用 DOM 元素没有太大区别。您只需确保在正确的 windowdocument 对象上调用您使用的方法。但是,一旦您正确定位了 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/

【讨论】:

  • 您好,很抱歉回复晚了,但这会替换
  • 哦,我没听懂。请参阅编辑,您可以使用 execcommand 和选择对象保持相同的逻辑
  • 谢谢,就是这样。我只是作为一个小奖励,如果你写“嘿”这个词并快速按空格,它不会取代?任何原因
  • 可能是因为按键干扰了功能。也许将功能一分为二,验证是否应在 keydown 上进行替换,然后在 keyup 上进行实际替换将解决此问题。我会在今天晚些时候尝试更新。
  • 查看编辑,最后它可以使用 onkeydown 而不是 onkeyup 以几乎相同的方式工作。验证需要有点不同,但它的工作原理几乎相同。而且这样更稳定。
猜你喜欢
  • 2017-08-23
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
相关资源
最近更新 更多