[英]Modernizr Media query doesn’t work when resize browser
我在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>
目前它仅运行一次(在页面加载时),因此当然只有在刷新页面时才会更改。
解决方案:您需要运行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>
我现在使用的常见替代方法是在onload
结束时简单地触发窗口resize
事件(例如,在连接处理程序之后)。
<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/
选项2中的上述答案很棒
帮助我很大,因为我有同样的问题,没有看到我的更改反映在初始页面调整大小。 导致初始window.resize
节省了一天。
为了使选项2中的上述解决方案更加清晰,我创建了一个mediaQ
变量,它存储在if语句中。 这个un混乱了if语句。 我还将#secondary
id存储在变量中。
$(window).resize(function(){
var mediaQ = Modernizr.mq('only screen and (max-width:767px)');
var secondaryId = $("#secondary");
// if mediaQ is true
if(mediaQ){
secondaryId.addClass("small");
secondaryId.css("margin", " 25px");
// if mediaQ is false
} else {
secondaryId.removeClass("small");
secondaryId.css("margin", "");
}
}).resize();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.