[英]Highlight text within an iframe
I am trying to highlight text which is inside of an iframe. 我正在尝试突出显示iframe内的文本。
Outside of an iframe, it works perfectly: 在iframe外部,它可以完美运行:
$('p').highlight('text');
To highlight text within an iframe, I used the following code but it doesn't work: 为了突出显示iframe中的文本,我使用了以下代码,但是它不起作用:
$( 'iframe' ).contents().find('html').highlight('domain');
https://jsfiddle.net/1tvsj8ho/ https://jsfiddle.net/1tvsj8ho/
On jsfiddle you may get an error (Blocked a frame with origin) but to me that's not important, since I am using a local file. 在jsfiddle上,您可能会遇到错误(将原点阻塞框架),但对我而言这并不重要,因为我使用的是本地文件。
Assuming the files are on the same domain at a real (non- file://
) URL, so you have no CORS restrictions to worry about, you should be able to do this by waiting for the iframe's load event to fire before calling your highlight function: 假设文件位于真实(非file://
)URL的同一域中,因此您无需担心CORS限制,那么应该可以通过在调用iframe的load事件之前触发它来做到这一点高亮功能:
$(function() { // document ready for parent window
// highlight in the parent:
$('p').highlight('text');
// highlight inside iframe...
$('iframe').on('load', function() { // ...when it's ready
$(this).contents().find('p').highlight('text')
});
});
(It's unfortunately difficult to demonstrate this in a snippet, due to those very same CORS restrictions, but I've tested this on my own localhost and it does work provided the highlight()
function is defined in the parent window.) (不幸的是,由于这些相同的CORS限制,很难在一小段中对此进行演示,但是我已经在自己的本地主机上对其进行了测试,并且只要在父窗口中定义了highlight()
函数,它就可以工作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.