使用javascript触发媒体查询

时间:2016-05-29 19:06:06

标签: javascript jquery css media-queries

单击带有Javascript的按钮时是否可以触发媒体查询public GameObject star; (没有浏览器宽度真的 <600px)< / p>

&#13;
&#13;
@media (max-width: 600px) { .a { ... } }
&#13;
// $('#b').click(function(){ // trigger the media query });
&#13;
.a { background-color: green; }

@media (max-width: 600px) { 
    .a { background-color: yellow; /* many other rules */ }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

您无法使用JavaScript触发媒体查询样式,但可以使用单独的样式表并修改其media属性来启用它们。这就是我的意思:

<强>的index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" media="all" href="regular_styles.css">
    <link rel="stylesheet" media="(max-width: 600px)" href="small_screen.css" id="small">
</head>
<body>

    <div class="a">Hello</div>
    <input id="b" type="button" value="Change" />

    <script src="jquery.min.js"></script>
    <script>
        $('#b').click(function(){
            // set the media query perimeter to "all"
            $('#small').attr('media', 'all');
        });
    </script>
</body>
</html>

<强> regular_styles.css

.a { background-color: green; }

<强> small_screen.css

.a { background-color: yellow; /* many other rules */ }