使用 javascript 触发媒体查询

Bas*_*asj 3 javascript css jquery media-queries

@media (max-width: 600px) { .a { ... } }单击带有 Javascript 的按钮时是否可以触发媒体查询?(没有浏览器宽度真的< 600px)

// $('#b').click(function(){ // trigger the media query });
Run Code Online (Sandbox Code Playgroud)
.a { background-color: green; }

@media (max-width: 600px) { 
    .a { background-color: yellow; /* many other rules */ }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a">Hello</div>
<input id="b" type="button" value="Change" />
Run Code Online (Sandbox Code Playgroud)

ble*_*lex 5

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

索引.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>
Run Code Online (Sandbox Code Playgroud)

常规样式.css

.a { background-color: green; }
Run Code Online (Sandbox Code Playgroud)

small_screen.css

.a { background-color: yellow; /* many other rules */ }
Run Code Online (Sandbox Code Playgroud)