javascript - 如何在具有角度的 iframe 中找到子节点并设置它们的样式?
问题描述
我需要一种方法来找到带有角度的 iframe 内的子节点(我需要 html 元素)。我目前的方法如下所示:
我在 iframe 中放置了一个参考变量(#privacyPolicy)
<iframe
name="privacy-policy"
id="privacy-policy"
[src]="myURL"
#privacyPolicy>
</iframe>
在我的组件中,我使用 @ViewChild 来访问我的 iframe
export class MyClass implements AfterViewInit {
@ViewChild('privacyPolicy', { static: false }) privacyPolicy: ElementRef<any>;
ngAfterViewInit() {
const hostElement = this.privacyPolicy.nativeElement;
console.log(hostElement.children);
console.log(hostElement.parentNode);
console.log('iframe', this.privacyPolicy.nativeElement.style.border = '1px solid black');
}
}
console.log()
生命周期中的第三个ngAfterViewInit()
正在工作并设置 iframe-Element 的样式。但我想为嵌套在 iframe-Element 中的 html-Element 设置样式。
我已经这样尝试过了(没有成功):
hostElement.children[0].style.border = "1px solid black";
有没有一种干净简单的 Angular 方法来完成这项工作?
解决方案
您需要访问 contentDocument,然后从 iframe 获得内容 HTML。在你的情况下:
const hostElement = this.privacyPolicy.nativeElement;
hostElement.contentDocument.body.style.border = '1px solid black';
如果您想为 iframe 添加新样式
const hostElement = this.privacyPolicy.nativeElement;
const iframe = hostElement.contentDocument;
const style = document.createElement('style');
let newStyle = 'body {background-color: red;}';
style.innerText = newStyle;
iframe.head.appendChild(style);
推荐阅读
- ruby-on-rails - 如何检查 url/链接在 ruby on rails 中是否安全
- c# - 创建无基图
- rust - 理解在迭代器上调用方法两次时如何满足借用检查器?
- templates - 这些将安全数组转换为 std::list 对象的方法可以转换为模板函数吗?
- oracle - 如何在 JPA 中插入属于 EmbeddedId 的元素的值?
- php - 当我使用准备好的语句进行搜索日期输入时出现致命错误
- python - 使用 numpy 数组列值的条件过滤 Pandas DataFrame
- amazon-web-services - 使用 MFA 与 EC2 和 RDS 建立 SSH 连接
- sql-server - SQL 查询 - CASE STATEMENT 返回 2 行或更多行 - 从中选择一个值
- server - Roudcube 版本 1.4.4 电子邮件详细信息的加载时间长