2017-08-04 181 views
-3

首先,似乎有很多具有相同类型标题的帖子,但没有一个关注我正面临的问题。这就是为什么我打开这个新问题的原因,我希望标题足够明确。使用页面.css文件将CSS添加到iframe元素

我正在自己的文本编辑器上工作,起初我使用的是<textarea>,但我想为我写的元素添加各种样式。在阅读了很多关于它的主题之后,我决定将<textarea>更改为。

在尝试任何新的设计或任何东西之前,我希望在此和我以前的<textarea>具有相同的行为。但我现在面临一个问题:

我元素是在一个页面,的index.html,这是一个CSS文件链接,的style.css。我能够改变style.css框架的全局设计(如宽度,高度,边框...),但是我不能在的元素中添加特殊设计,属性为I添加在我的style.css中

我在iframe中有任何标记 Here is the #document tag

但是即使我想这个奇怪的标签添加到CSS的样式不应用于我想改变的元素之前#document检查员看到。

所以为了简洁起见,我的问题是这样的:是否可以在主页面的样式表文件中的iframe中添加一些样式?

以下是我的代码的一些相关部分,它显示了我想要执行的操作:向中的<p>标记添加自定义字体。从父

window.onload = function() { 
 
    var frameElement = document.getElementById("text-field"); 
 
    var doc = frameElement.contentDocument; 
 
    doc.body.contentEditable = true; 
 
}
html, body { 
 
\t margin : 0px; 
 
\t background : #f5f5f5; 
 
\t font-family: 'Roboto', sans-serif; 
 
} 
 

 
input:focus, textarea:focus { 
 
\t outline: none; 
 
} 
 

 
.text-editor { 
 
\t min-width : 800px; 
 
\t width : 1200px; \t 
 
\t max-width : 1600px; 
 
\t min-height : 400px; 
 
\t height : 850px; 
 
\t max-height : 850px; 
 
\t background : #f0f0f0; 
 
\t box-shadow : 0px 1px 4px #ccc; 
 
\t margin : auto; 
 
\t overflow:auto 
 
} 
 

 
.text-editor .text-field { 
 
\t display : block; 
 
\t background-color : white; 
 
\t min-height : 300px; 
 
\t height : 600px; 
 
\t max-height : 600px; 
 
\t width : 90%; 
 
\t margin : auto; 
 
\t padding : 5px; 
 
\t border: 1px solid #ccc; 
 
} 
 

 
.text-editor .text-field #document html body { 
 
\t font-family: 'Source Code Pro', monospace; 
 
\t font-size : 14px; 
 
}
<!DOCTYPE html> 
 

 
<html> 
 

 
\t <head> 
 
\t \t <title>A Text Editor Project</title> 
 
\t \t <link rel="stylesheet" type="text/css" href="CSS/style.css"> 
 
\t \t <link href="https://fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet"> 
 
\t \t <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet"> 
 
\t \t <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
\t </head> 
 
\t 
 
\t <body> 
 
\t \t 
 
\t \t <div class="text-editor"> 
 
\t \t \t <iframe class="text-field" id="text-field" src="about:blank" contenteditable="true"> 
 
\t \t \t 
 
\t \t \t </iframe> 
 
\t \t </div> 
 
\t 
 
\t </body> 
 

 
</html>

+0

相反iframe的你可以尝试

Sanil

+0

@Foaster如果你试过你读了第一个答案的评论,你会看到,这个解决方案是完全过时并且在HTML5中无效。 –

+0

@Sanil由于各种原因,包括安全问题,我想使用iframe,因为我阅读了很多关于此主题的建议。 –

回答

2

样式将不会被施加到iframe中的文档。最好的解决方案是将样式表添加到iframe中的文档中。通过javascript或创建一个模板页面通过src加载。

喜欢的东西:

var head = doc.head 
    var link = doc.createElement('link') 
    link.type = 'text/css' 
    link.rel = 'stylesheet' 
    link.href = ...src... 
    head.appendChild(link) 
在现有的JavaScript

我已经把一个小例子,有一个样式块here

相关问题