简体   繁体   中英

Remove Certain CSS Style from Html Page

I have a Html page which has anchor tag, I Need to remove certain style applied already in html page for anchor tag while the html page is opened throw Iframe.

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;
}

But inside "iframe" also these styles has been applying.

You have to first detect if your page is rendered inside an iframe and in that case apply an alternative CSS. It' can't be done with vanilla CSS then it has to be done with some 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>

Code to load CSS from JavaScript is from How to load up CSS files using Javascript? .

With all that code you may simply write (even just after that inside <script> block):

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

Of course same technique can be applied to patch CSS with iframe specific styles:

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

i dont know how to detect if page is opened in iframe or not, but there is one possible(not very nice) workaround, you can set iframe to width which is not commonly used by devices (example 463px) and then set media query for this resolution which apply when content is shown in this iframe. This is really nasty way since its not 100% and i would not recommending that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM