我想使用matchmedia.addlistener要检查窗口大小,我的按钮事件如下所示
$('button').click(function(){
if(this.attr('aria-expanded') === 'false'){
$this.attr('aria-expanded', true).next().fadeOut();
}else{
$this.attr('aria-expanded', false).next().fadeIn();
}
});
如果我使用matchmedia
,我需要这样做
minWidth768 = window.matchMedia('(min-width: 768px)');
if(minWidth768.matches){
$('button').click(function(){
if(this.attr('aria-expanded') === 'false'){
$this.attr('aria-expanded', true).next().slideUp();
}else{
$this.attr('aria-expanded', false).next().slideDown();
}
});
}else{
$('button').click(function(){
if(this.attr('aria-expanded') === 'false'){
$this.attr('aria-expanded', true).next().fadeOut();
}else{
$this.attr('aria-expanded', false).next().fadeIn();
}
});
}
如果我想添加一个addListener
,那么我需要再次重复我的代码。
minWidth768.addListener(function(media) {
if(media.matches){
//repeat;
}else{
//repeat;
}
});
有没有一种方法可以让我的代码更短,并使代码看起来漂亮且易于维护?
最佳答案
您可以创建一个函数,然后在需要的地方调用该函数。
例如。
function matchMedia(){
//do stuff here
}
//now call where you want
if(true){
matchMedia();
}
但请注意:如果您想在函数参数内调用函数,则无需使用括号,如下例所示:
setTimeout(matchMedia, 400);// don't do matchMedia()
关于javascript - 使用 matchmedia 时缩短代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25152730/