我有一个 jQuery 函数,只有当某个媒体查询为真(就绪和调整大小时)时才应触发该函数。
我发现了一个很酷的技巧来检查某个媒体查询是否为真:
HTML
<div id="isthin"></div>
CSS
#isthin {
display: inline-block;
content: '';
width: 1px;
height: 1px;
overflow: hidden;
}
@media only screen and (max-width: 1047px) {
#isthin {
display: none;
}
}
jQuery
$(document).ready(function(){
if ( $('#isthin').is(":visible") ) {
// function should be fired
} else {
// function should not be fired
}
});
$(window).resize(function(){
if ( $('#isthin').is(":visible") ) {
// function should be fired
} else {
// function should not be fired
}
});
独立的 jQuery 函数
$(function () {
$('nav li ul').hide().removeClass('sub-nav');
$('nav li').hover(function () {
$('ul', this).stop().slideToggle(300);
});
});
这是我的逻辑,但不知何故,当媒体查询发生变化时,该函数仍然在调整大小时运行。
最佳答案
根据您的代码片段,我用浏览器打开了此脚本:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style type="text/css">
#isthin {
display: inline-block;
content: '';
width: 1px;
height: 1px;
overflow: hidden;
border: 1px solid red;
}
@media only screen and (max-width: 1047px) {
#isthin {
display: none;
}
}
</style>
<script type="text/javascript">
$(document).ready(function(){
if ( $('#isthin').is(":visible") ) {
// function should be fired
console.log("[doc ready] Media Query wide");
} else {
// function should not be fired
console.log("[doc ready] Media Query thin");
}
});
$(window).resize(function(){
if ( $('#isthin').is(":visible") ) {
// function should be fired
console.log("[Resize] Media Query wide");
} else {
// function should not be fired
console.log("[Resize] Media Query thin");
}
});
</script>
</head>
<body>
<div id="isthin"><id>
</body>
</html>
如果我再次将浏览器拉窄和拉宽,我会看到控制台消息,因为它们应该是:
[doc ready] Media Query wide
[Resize] Media Query wide
[Resize] Media Query wide
[Resize] Media Query wide
[Resize] Media Query wide
...
...
[Resize] Media Query thin
[Resize] Media Query thin
[Resize] Media Query thin
[Resize] Media Query thin
...
[Resize] Media Query wide
...
...
因此,我认为您检测媒体查询的方式是正确的(并且复杂的)。我建议你检查一下:
- 如果是浏览器特定问题,
- 单独的 jQuery 函数如何链接到调整大小回调。
然后,请考虑在这种情况下,您不会通过使用 CSS 查询来节省一些工作。无论如何,您都需要调整大小回调。因此,请观看我见过的解决此问题的另一种优雅方法。恰恰相反,避免使用 CSS 选择器,但做同样的事情:
$(window).resize(function(){
if ( $(window).width() < xxxx && $(window).width() > yyyyy ) {
$('body').addClass('phone'); // <<<<<<<<<<<<<<
$('body').removeClass('tablet');
$('body').removeClass('workstation');
} else if ( ... ) {
$('body').removeClass('phone');
$('body').addClass('tablet'); // <<<<<<<<<<<<<<
$('body').removeClass('workstation');
}
...
...
}
然后,您可以通过将 .phone、.tablet 和 .workstation 添加到选择器来在 CSS 中轻松区分,并且可以删除查询。进一步:
$(window).resize(function(){
if ($('body').hasClass('phone')) {
...
...
} else if ( ... ) {
...
}
...
...
}
像这样,你在 JS 端拥有了所有的东西,而在 CSS 端则拥有了更少的东西。
这个想法不是我提出的,我在一个框架中看到了它,但我不确定它是哪一个。
关于jQuery:仅当某些媒体查询为真时才触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24289752/