Javascript 使用matchmedia时缩短代码
我想使用检查窗口大小,我的按钮事件如下所示Javascript 使用matchmedia时缩短代码,javascript,jquery,Javascript,Jquery,我想使用检查窗口大小,我的按钮事件如下所示 $('button').click(function(){ if(this.attr('aria-expanded') === 'false'){ $this.attr('aria-expanded', true).next().fadeOut(); }else{ $this.attr('aria-expanded', false).next().fadeIn(); } }); 如果我使用matc
$('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;
}
});
有没有一种方法可以使代码更短,使代码看起来更漂亮,更易于维护?您可以创建一个函数,然后在需要时调用该函数 例如 但请注意:如果要在函数参数内调用函数,则无需使用括号,例如:
setTimeout(matchMedia, 400);// don't do matchMedia()
setTimeout(matchMedia, 400);// don't do matchMedia()