我很难让一些响应式js工作。我有5个断点,期望的结果是断点处于活动状态时匹配js函数,而当断点不再处于活动状态时匹配不匹配。
以下是我采取的方法。我遇到的问题是不匹配,它的工作原理是从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]);
}
答案 0 :(得分:0)
我相信我明白了。我改变了不匹配的方式
var breakpoints = {
bp1: //.....,
bp2: //.....,
//.....
bp5: //.....
};
var queries = {
bp1: {
match: function() {
console.log('smalltouch portrait');
//...
},
unmatch: function() {
console.log('unmatch smalltouch portrait');
//...
}
},
bp2: {
match: function() {
console.log('smalltouch landscape');
//...
},
unmatch: function() {
console.log('unmatch smalltouch lanscape');
//...
}
},
//.....
bp5: {
match: function() {
console.log('standard desktop');
//...
},
unmatch: function() {
console.log('unmatch standard desktop');
//...
}
}
};
var prevBreakpoint = '';
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);
if (data.matches === true) {
if (prevBreakpoint) {
queries[prevBreakpoint].unmatch();
}
queries[breakName].match();
prevBreakpoint = breakName;
}
}
// run the callback on current viewport
cb({
media: query,
matches: matchMedia(query).matches
});
// subscribe to breakpoint changes
matchMedia(query).addListener(cb);
}(name, breakpoints[name]);
}