调整大小浏览器时,Modernizr Media查询不起作用

use*_*514 6 javascript jquery media-queries modernizr

我在JavaScript中使用Modernizr媒体查询来更改元素边距并添加"小"类.当我调整浏览器大小时,我的Modernizr媒体查询不起作用,但是当我刷新页面时,它可以工作.我知道我可以使用jQuery $( window ).resize()函数解决这个问题,但我想用媒体查询来解决它.任何人都能告诉我如何解决这个问题吗?

<html class="no-js">
    <head>
        <title>Foundation 5</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="modernizr.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                if (Modernizr.mq('(max-width: 767px)')) {
                    $("#secondary").addClass("small");
                    $("#secondary").css("margin", " 25px");
                }
            });
        </script>
        <style type="text/css">
            #primary {
                width: 300px;
                height: 200px;
                background-color: black;
            }
            #secondary {
                margin: 0 auto;
                width: 250px;
                height: 150px;
                background-color: white;
                position: absolute;
            }

        </style>
    </head>
    <body>
        <div id="primary">
            <div id="secondary">

            </div>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Gon*_*ing 13

目前它仅运行一次(在页面加载时),因此当然只有在刷新页面时才会更改.

解决方案:您需要运行onload 以及浏览器/窗口调整大小时运行代码.:

例如

<script type="text/javascript">
    var mod = function(){
        if (Modernizr.mq('(max-width: 767px)')) {
            $("#secondary").addClass("small").css("margin", " 25px");
        } else {
            // Clear the settings etc
            $("#secondary").removeClass("small").css("margin", "");   // <<< whatever the other margin value should be goes here
        }
    }

    // Shortcut for $(document).ready()
    $(function() {
        // Call on every window resize
        $(window).resize(mod);
        // Call once on initial load
        mod();
    });
</script>
Run Code Online (Sandbox Code Playgroud)

选项2

我现在使用的常见替代方法是简单地resize在结束时触发窗口事件onload(例如,在连接处理程序之后).

<script type="text/javascript">

    // Shortcut for $(document).ready()
    $(function() {
        // Call on every window resize
        $(window).resize(function(){
            if (Modernizr.mq('(max-width: 767px)')) {
                $("#secondary").addClass("small").css("margin", " 25px");
            } else {
                // Clear the settings etc
                $("#secondary").removeClass("small").css("margin", "");   // <<< whatever the other margin value should be goes here
            }
        }).resize();   // Cause an initial widow.resize to occur
    });
</script>
Run Code Online (Sandbox Code Playgroud)

简单的JSFiddle示例: http ://jsfiddle.net/TrueBlueAussie/zv12z7wy/