第三天,我试图用JavaScript实现媒体查询。
说函数A()仅在(最小宽度:768像素)时被调用,函数B()仅在(最大宽度:767px)时才能被调用。
这可以通过使用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
});
}
});
这应该工作:
$(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
条件匹配,则运行代码,否则不运行代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句