【发布时间】:2014-06-20 10:41:01
【问题描述】:
第三天我正在尝试用 JavaScript 实现媒体查询。
说函数 A() 只能在 (min-width: 768px) 时调用, 并且只有在 (max-width: 767px) 时才能调用函数 B()。
这很容易通过使用 MediaQueryList 对象来实现。但是浏览器调整大小会出现问题。
- 如果页面已加载,则无法调用函数 A() (max-width: 767px),然后调整为 (min-width: 768px)。
- 如果我尝试在调整窗口大小时调用函数,则函数 A() 会在单击时触发多次。
我尝试了不同的解决方案:
- 使用 addListener
- enquire.js
- setTimeout / clearTimeout — http://go.shr.lc/1kGNpM6
等
但显然我的 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
});
}
});
【问题讨论】:
标签: javascript jquery