我有一个带有 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/