我对 iframe 中的媒体查询有疑问。我发现只要我不指定方向,我的媒体查询似乎就可以工作。 这个媒体查询工作得很好:
@media
screen and (-webkit-min-device-pixel-ratio: 1) and (max-device-width: 1024px),
screen and ( min--moz-device-pixel-ratio: 1) and (max-device-width: 1024px),
screen and ( -o-min-device-pixel-ratio: 1/1) and (max-device-width: 1024px),
screen and ( min-device-pixel-ratio: 1) and (max-device-width: 1024px) {
/*Styles here*/
}
但是当我添加 orientation 属性时,它不再起作用(无论是 orientation: portrait 还是 orientation: landscape):
@media
screen and (-webkit-min-device-pixel-ratio: 1) and (max-device-width: 1024px) and (orientation: portrait),
screen and ( min--moz-device-pixel-ratio: 1) and (max-device-width: 1024px) and (orientation: portrait),
screen and ( -o-min-device-pixel-ratio: 1/1) and (max-device-width: 1024px) and (orientation: portrait),
screen and ( min-device-pixel-ratio: 1) and (max-device-width: 1024px) and (orientation: portrait) {
/*Styles here*/
}
类似的媒体查询在我的主 CSS 中工作得很好,但这个问题只出现在 iframe 中使用的 CSS 文件中。任何人有任何想法如何解决这个问题? 是否可以从 iframe CSS 检测方向?我真的很希望得到一些帮助!
看来其他人也有同样的问题,但我找不到解决问题的方法。
编辑: 只是为了澄清一些含糊之处,我已经在几个移动设备上测试了该网站,但我尝试使用此设备主要针对平板电脑。
最佳答案
这可能是一个糟糕的解决方案,但至少它是有效的,因为我同时控制了主页和 iframe 中显示的页面,所以我看不出应该有任何直接的危险.无论如何,这是我的解决方案:
我有一个想法,这个问题可能可以用 javascript 代替 CSS 来解决。但是即使使用javascript我仍然无法获得正确的方向,所以我猜这个问题实际上源于iframe中的页面对其父环境一无所知。但是,我发现如果方法位于名为 parent.js 的文件中,则可以从主页的 javascript 调用方法。这使得创建一个方法来检查主页的方向并从 iframe 的 javascript 调用它成为可能。该解决方案当然适用于任何其他类似问题。但是,它确实要求您可以访问主页代码和 iframe 中加载的页面。
编辑:正如 muzzamo 在评论中提到的那样,此解决方案是否要求主页代码和 iframe 代码位于同一域中。抱歉不清楚! -编辑结束-
来自 parent.js 的代码:
function getDeviceOrientation() {
var devOri = window.orientation;
return devOri;
}
来自 iframe.js 的代码:
function changeFontSize() {
var parentOrientation = parent.getDeviceOrientation();
//do stuff dependent on value of parentOrientation or whatever
}
如前所述:我不确定这是一个好的解决方案,但至少它是一个解决方案。由于我是 javascript 的新手,我仍然希望对我的解决方案和/或其他(更好的)问题解决方案发表评论。但我希望这能帮助其他有类似问题的人!
附言。不要忘记在 HTML 文件的头部也包含 parent.js 文件!
<script type="text/javascript" src="js/parent.js"></script>
关于css - 为什么包含方向属性的媒体查询在 iframe 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17105664/