Javascript 更改 iframe 内的字体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25963616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:09:41  来源:igfitidea点击:

Change font inside an iframe

javascripthtmlcssiframe

提问by Abbas

I have a HTML page that have an iframe. I want to change style of iframe content but I don't seem to be able to do so.

我有一个带有iframe. 我想更改 iframe 内容的样式,但我似乎无法这样做。

I want to change the font of all content inside the iframeto "Tahoma". This is my code:

我想将里面所有内容的字体更改iframe为“Tahoma”。这是我的代码:

<!DOCTYPE>

<html>
<head>

<title>phpinfo()</title>
<style type="text/css">
#outerdiv
{
width:446px;
height:246px;
overflow:hidden;
position:relative;
}

#inneriframe
{
position:absolute;
top: -508px;
left: 0px;
width: 100%;
height: 615px;
font-family: Tahoma;
}
</style>

<script>
onload = function()
{
 document.frm.document.body.style.fontFamily = "Tahoma";
}
</script>

</head>

<body>
<div id='outerdiv '>
<iframe  name="iframe" src="http://m.sarafikish.com" id='inneriframe' name="frm" scrolling=no frameborder="0"  > </iframe>
</div>    
</body></html>

回答by Alexander O'Mara

This is only possible if the iframe's srcis set to a page on the same domain or otherwise satisfies the Same-Origin Policy. Your question does not specify if you meet these requirements, but if you do, you can use the contentDocumentproperty of the iframeto manipulate the iframe through JavaScript.

这只有在iframe'ssrc设置为同一域上的页面或满足同源策略时才可能。您的问题没有说明您是否满足这些要求,但是如果满足,您可以使用contentDocumentiframe属性通过 JavaScript 操作 iframe。

Example:

例子:

document.getElementById("inneriframe").contentDocument.body.style.fontFamily = "Tahoma";

回答by j4r3k

var frame = $('#frameId');
frame.load(function () {
    frame.contents().find('body').css('font-family', 'Arial');
}

If you want to use custom font:

如果要使用自定义字体:

var frame = $('#frameId');
frame.load(function () {
    var head = frame.contents().find('head');
    $('<link/>', {
        rel: "stylesheet",
        type: "text/css",
        href: "/url/to/style_with_fonts.css"
    }).appendTo(head);
    frame.contents().find('body').css('font-family', 'Custom Font');
}