html - 从 Html 页面中删除某些 CSS 样式

标签 html css iframe

我有一个带有 anchor 标记的 Html 页面,当打开 html 页面并抛出 Iframe 时,我需要删除已在 html 页面中为 anchor 标记应用的某些样式。

HTML Content as below:

<html>
<body>
<div>some content<a href="http://www.website.com" name="test1"/> some content </div>
</body>
</html>

I tried as below:

    a[name^="test1"]:before{
content:"[prefix text]";
display:inline;
color:red;
}
a[name^="test1"]:after{
content:"suffix text";
display:inline;
color:green;
}
iframe a[name^="test1"]:before{
display:none;
}
iframe a[name^="test1"]:after{
display:none;
}

但在“iframe”中也应用了这些样式。

最佳答案

您必须首先检测您的页面是否在 iframe 中呈现在这种情况下应用替代 CSS。它不能用 vanilla CSS 来完成,那么它必须用一些 JavaScript 来完成:

<script type="text/javascript">
    function getTopWindow() {
        try {
            return window.top;
        } catch {
            // If we can't access window.top then browser is restricting
            // us because of same origin policy. 
            return true;
        }
    }

    function isRendererdInFrame() {
        // If top window is null we may safely assume we're in iframe
        return window.self !== getTopWindow();
    }

    function loadCss(location) {
        if(document.createStyleSheet) {
            document.createStyleSheet('http://server/stylesheet.css');
        } else {
            var styles = "@import url('" + location + "');";
            var newSS=document.createElement('link');
            newSS.rel='stylesheet';
            newSS.href='data:text/css,'+escape(styles);
            document.getElementsByTagName("head")[0].appendChild(newSS);
        }
    }
</script>

从 JavaScript 加载 CSS 的代码来自 How to load up CSS files using Javascript? .

有了所有这些代码,您可以简单地编写(甚至在 <script> block 内):

var cssToLoad = isRendererdInFrame() ? "iframe.css" : "not-iframe.css";
loadCss("http://server/" + cssToLoad);

当然,同样的技术可以应用于补丁 CSS iframe具体样式:

if (isRenderedInFrame())
    loadCss("http://server/iframe-patch.css");

关于html - 从 Html 页面中删除某些 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31158641/

相关文章:

html - 相邻兄弟 : too many elements between the rules

java - swing java app 和 iframe - 双向通信

javascript - 将 <div> 标记放置在基本图像上并允许调整大小的最佳方法是什么?

javascript - 单击按钮更改日期

html - 防止内容隐藏在固定位置导航栏后面

html - 垂直对齐单元格中的文本

html - 日期字段大小(在所有情况下)大于 ASP.Net 中列中的所有其他字段

javascript - 如何在cshtml中的$(document).ready(function())中使用if条件?

javascript - 使用 iframe 和 ontouchstart 的 Mobile Safari 中的文本选择错误

html - 即使在 div 中,转换(缩小)的 iframe 仍然占用空间