有没有办法将外部样式表注入iframe?
我有一个网站,该网站在页面的一侧有一个编辑器,左侧有一个iframe。当前,当您在编辑器内输入HTML代码时,将在键盘上自动更新IFRAME。我希望在编辑器中输入的代码在iFrame中具有默认样式。因为这是一个游戏,您输入html标记将设置的项目是默认标签(H1,P,DIV等)。因此,我无法在HTML文档中使用样式,因为它将在整个页面上进行样式,而不仅仅是IFRAME中的项目。我想拥有一个包含在iframe中的外部样式表,因此我可以在不影响index.html页面的情况下对标签进行样式。
<style>
* {
padding: 0;
margin: 0;
}
html {
display: flex;
justify-content: center;
}
h2 {
color: rgba(255, 255, 255, 0);
width: 300px;
height: 50px;
margin: 10px;
background-color: crimson;
}
</style>
<iframe src="" frameborder="0" class="iframe"></iframe>
JS
editor.addEventListener('keyup',()=>{
var html = editor.textContent;
iframe.src = "data:text/html;charset=utf-8," + encodeURI(html) + "<style>" + style.textContent + "</style>";
});
I have a website that has an editor on one side of the page and an iframe on the left. Currently, the iframe is updated automatically on keyup when you enter HTML code inside the editor. I would like the code entered in the editor to have default styling within the iframe. Because it's a game where you enter HTML tags the items that will be styled are the default tags (h1, p, div, etc). Because of this, I can't have styling within the HTML document because it will style the items on the entire page rather than just items in the iframe. I would like to have an external style sheet that is contained within the iframe so I can style the tags without affecting the index.html page.
<style>
* {
padding: 0;
margin: 0;
}
html {
display: flex;
justify-content: center;
}
h2 {
color: rgba(255, 255, 255, 0);
width: 300px;
height: 50px;
margin: 10px;
background-color: crimson;
}
</style>
<iframe src="" frameborder="0" class="iframe"></iframe>
JS
editor.addEventListener('keyup',()=>{
var html = editor.textContent;
iframe.src = "data:text/html;charset=utf-8," + encodeURI(html) + "<style>" + style.textContent + "</style>";
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,确定为什么不。他们是2个不同的文件。
如果您坚持使用外部CSS,则代替
&lt; style&gt;
标签添加&lt; link rel =“ stylesheet” href =“ https://example.com/style.com/style.css” &gt;
to iframe的HTML。Yes sure why not. They are 2 different documents.
If you insist on using external css, then instead of
<style>
tag add<link rel="stylesheet" href="https://example.com/style.css">
to the HTML of the iframe.