Media queries leaking across frames

2020-05-23 05:36发布

问题:

Here's some HTML:

<iframe src="test.html" style="width: 200px; height: 100px;"></iframe>
<iframe src="test.html" style="width: 800px; height: 100px;"></iframe>

The test.html page contains some CSS from an external file:

<link rel="stylesheet" type="text/css" href="style.css" />

And the stylesheet has:

@media all and (max-width: 600px) {
  body {background-color: red;}
}

The above is simplified, but enough to demonstrate the issue: Both pages are red, despite one of them clearly being wider than the other. Demonstration page

What gives?

(Note: Tested in IE and Chrome - Chrome was fine, with one frame red and the other white.)

回答1:

As you can read in this answer, Internet Explorer 9 supports CSS3 media queries, but not within frames when the CSS containing the media query is in an external file, so you should put your media query in the head of the test.html page. Previous IE versions don't support media queries natively, but you could use a javascript library (see respond.js or css3-mediaqueries-js) to overcome this problem.



回答2:

You can do the job by using jquery with the following script :

<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script>
    $(document).ready(function() {
        if ($(document).width() < 600) {
            $('body').css('background-color', 'red');
        };
    });
</script>