0
我有困難得到一些響應js的工作。我有5個斷點,期望的結果是js函數在斷點處於活動狀態時匹配,而在斷點不再處於活動狀態時不匹配。匹配和無匹配的響應JavaScript與.matchMedia()
以下是我採取的方法。我遇到的問題是不匹配,它的工作原理是從bp1 - > bp5,而不是bp5 - > bp1。
任何幫助表示讚賞
var breakpoints = {
bp1: //.....,
bp2: //.....,
//.....
bp5: //.....
};
var queries = {
bp1: {
match: function() {
console.log('smalltouch portrait');
//...
},
unmatch: function() {
console.log('unmatch smalltouch portrait');
//...
},
active: false
},
bp2: {
match: function() {
console.log('smalltouch landscape');
//...
},
unmatch: function() {
console.log('unmatch smalltouch lanscape');
//...
},
active: false
},
//.....
bp5: {
match: function() {
console.log('standard desktop');
//...
},
unmatch: function() {
console.log('unmatch standard desktop');
//...
},
active: false
}
};
for (var name in breakpoints){
// need to scope variables in a for loop
!function(breakName, query) {
// the callback
function cb(data){
// add class name associated to current breakpoint match
$('body').toggleClass(breakName, data.matches);
//unmatch previous matches
if (data.matches === false && queries[breakName].active) {
queries[breakName].unmatch();
queries[breakName].active = false;
}
//match to breakpoint
if (data.matches === true) {
queries[breakName].match();
queries[breakName].active = true;
}
}
// run the callback on current viewport
cb({
media: query,
matches: matchMedia(query).matches
});
// subscribe to breakpoint changes
matchMedia(query).addListener(cb);
}(name, breakpoints[name]);
}