第三天,我尝试用JavaScript实现媒体查询。
假设函数A()只能在(最小宽度:768px)时调用, 并且只有在(max-width:767px)时才能调用函数B()。
使用MediaQueryList对象可以轻松实现。但是浏览器调整大小会出现问题。
我尝试过不同的解决方案:
等
但很明显,我对JavaScript的了解并不足以做事。请帮忙
// Attempt #1 -----------------------------------------------------------------
function responsiveFunction(){
if(window.matchMedia('(max-width: 767px)').matches) {
$('.btn').click(function(event) {
// Knock knock
});
}
}
$(function(){
responsiveFunction();
});
$(window).resize(function(){
responsiveFunction();
});
// Attempt #2 -----------------------------------------------------------------
function responsiveFunction(mql) {
if (mql.matches) {
$('.btn').click(function(event) {
// Knock knock
});
}
}
var mql = window.matchMedia('min-width: 768px'); // MQL for MediaQueryList object
mql.addListener(responsiveFunction); // Execute responsive function on resize
responsiveFunction(mql); // Execute responsive function on load
// Attempt #3 -----------------------------------------------------------------
var smartResize = (function() {
var timers = {};
return function(callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = 'Don\'t call this twice without a uniqueId';
}
if (timers[uniqueId]) {
clearTimeout(timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
function responsiveFunction() {
if (window.matchMedia('(min-width: 768px)').matches) {
$('.btn').click(function(event) {
// Knock knock
});
}
}
// Execute responsive function on load
responsiveFunction();
// Execute responsive function on resize
$(window).resize(function() {
smartResize(function() {
responsiveFunction();
}, 500, 'myUniqueId');
});
// Attempt #4 w enquire.min.js ---------------------------------------------
enquire.register('(min-width: 768px)', {
match: function() {
$('.btn').click(function(event) {
// Knock knock
});
}
});
答案 0 :(得分:2)
这应该有效:
$(function(){
$('.btn').on('click', function(event) {
if(window.matchMedia('(max-width: 767px)').matches) {
// Only run the code if media query matches
}
});
});
注册click
处理程序而不检查max-width
并在运行代码之前检查width
,如果width
条件匹配则运行代码,否则不会运行代码。