javascript 如果在 iframe 中,则以不同方式显示页面 (css)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4353933/
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
Show page differently (css) if within iframe
提问by ThomasReggi
Is there any way to, as the title says "Show page differently (css) if within iframe". I'm looking for a jQuery / JavaScript method to potentially use a different css stylesheet if the site is within an iframe. Any ideas?
有什么办法可以,正如标题所说的“如果在 iframe 中以不同方式显示页面(css)”。如果站点位于 iframe 中,我正在寻找一种 jQuery / JavaScript 方法来潜在地使用不同的 css 样式表。有任何想法吗?
回答by Oded
You can injecta different stylesheet if the window is not the top window.
if (window.top!=window.self)
{
// In a Frame or IFrame
}
else
{
// Not in a frame
}
回答by Henrik N
Rather than inject a new stylesheet, I would suggest adding a CSS class to body.
与其注入新的样式表,我建议将 CSS 类添加到body.
jQuery example:
jQuery 示例:
$(function() {
if (window.self != window.top) {
$(document.body).addClass("in-iframe");
}
});
Now you can style things differently like
现在你可以设计不同的东西,比如
.in-iframe p {
background: purple;
}
回答by Jeremy Cook
Here is a fast and designer friendly approach using vanilla JS. Just one line of JS and the look and feel can be controlled from CSS/SASS/LESS.
这是使用 vanilla JS 的快速且设计人员友好的方法。只需一行 JS,就可以从 CSS/SASS/LESS 中控制外观和感觉。
Place this within the headelement before any CSS or JS is loaded:
在head加载任何 CSS 或 JS 之前将它放在元素中:
// Sets the class of the HTML element using vanilla JavaScript
document.documentElement.className += (window.self == window.top ? " top" : " framed");
Then in your CSS/SASS/LESS you can hide, show, and tweak based on which class was applied.
然后在您的 CSS/SASS/LESS 中,您可以根据应用的类来隐藏、显示和调整。
/* Hide site navigation when in an iframe */
html.framed .site-nav,
html.framed .site-footer {
display: none;
}
PSA: Consider taking advantage of the X-Frame-Optionsto keep your hard work from being hiHymaned.
PSA:考虑利用X-Frame-Options来防止您的辛勤工作被劫持。
回答by lbz
if( self != top ) {
headTag = document.getElementsByTagName("head")[0].innerHTML;
var frameCSS = headTag + '<style type="text/css">**insert CSS here**</style>';
document.getElementsByTagName('head')[0].innerHTML = frameCSS;
}
If the page is the only page being displayed, top, parent, self and window will be equal. If the page is being held within a frameset, self and top will not be equal. If the page is the page containing the frameset, and it itself is not being held within a frameset, self and top will be equal.
如果页面是唯一显示的页面,top、parent、self 和 window 将相等。如果页面被保存在框架集中,则 self 和 top 将不相等。如果页面是包含框架集的页面,并且它本身没有被保存在框架集中,则 self 和 top 将相等。

