使用javascript/Jquery突出显示iframe中的单词或句子 [英] Highlighting a word or sentence in iframe, using javascript/Jquery

查看:85
本文介绍了使用javascript/Jquery突出显示iframe中的单词或句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改iframe广告代码中单词的背景颜色.我能够搜索单词,但无法获得如何更改颜色的信息. 这是我的代码.

I am trying to change the background colour of word in iframe tag. I am able to search the word, but not getting how to change the colour. Here is my code.

$(document).ready(function () {
   $('#content').contents().find('head').append($("<style type='text/css'> .red{color:red;}</style>"));
   var cont = document.getElementById('content').contentWindow.document.body.innerHTML;
          
   if($("#content").contents().text().search("SEARCH WORD")!=-1){
     console.log("Found");
     //<span class="red"> SEARCH WORD </span>
   }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-left: 0px;" class="col-sm-8 text-center">
  <iframe id="content" ng-src="http://locahost:8888/public/textfiles/sample.txt" 
          width="100%" height="500px" align="middle"></iframe>&emsp;
</div>

推荐答案

如上所述,

As noted, CORS will not allow you to alter iFrames sourced from other domains you do not control without the proper CORS heading.

如果您在同一个域中,则可以执行一些操作,例如查找单词,对其进行更改,然后用新代码替换iframe的内容.这是工作小提琴和代码,例如:

If you are on the same domain, you can possibly do something like find the word, alter it, and then replace the contents of the iframe with your new code. Here is a working fiddle and code For example:

<iframe src="http://fiddle.jshell.net/_display/" id="myIframe"></iframe>
<script>
var searchWord = "error";
$(document).ready(function(){
    $('#myIframe').ready(function(){
        var $html = $($('#myIframe').contents().find('body').html());
     if($html.contents().text().search(searchWord)!=-1){
       console.log("Found");
       var replaceWith = "<span style='color:red'>"+searchWord+"</span>"
       var newHTML = $html.text().replace(searchWord, replaceWith);
       $('#myIframe').contents().find('body').html(newHTML);
     }
   });
});
</script>

这篇关于使用javascript/Jquery突出显示iframe中的单词或句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆