调整大小浏览器时,Modernizr Media查询不起作用 [英] Modernizr Media query doesn’t work when resize browser
问题描述
我在JavaScript中使用Modernizr媒体查询来更改元素边距并添加小类。当我调整浏览器大小时,我的Modernizr媒体查询不起作用,但当我刷新页面时,它可以工作。我知道我可以使用jQuery $(window).resize()
函数解决这个问题,但我想用媒体查询来解决它。任何人都可以告诉我如何解决这个问题吗?
I use a Modernizr media query in JavaScript to change an element margin and add a class "small". My Modernizr media query doesn't work when I resize my browser, but when I refresh the page then it works. I know I can solve this problem using the jQuery $( window ).resize()
function, but I want to solve it using a media query. Can any one tell me how I can solve this problem?
<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>
推荐答案
目前仅运行一次(在页面加载时) ),所以当然只有在你刷新页面时它才会改变。
At the moment it runs once only (on page load), so of course it only changes when you refresh the page.
解决方案:你需要你的代码来运行onload 和当浏览器/窗口调整大小时。 :
Solution: You need your code to run onload and when the browser/window resizes. :
例如
<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>
选项2
常见的替代方案I现在用来简单地在 onload
的末尾触发一个窗口 resize
事件(例如在连接处理程序之后) 。
Option 2
A common alternative I now use is to simply trigger a window resize
event at the end of the onload
(e.g. after the handler is connected).
<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>
简单JSFiddle示例: http://jsfiddle.net/TrueBlueAussie/zv12z7wy/
这篇关于调整大小浏览器时,Modernizr Media查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!