javascript - 使用 matchmedia 时缩短代码

标签 javascript jquery

我想使用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/

相关文章:

jquery - 设置 'visibility: visible' 不起作用

jquery - Fullcalendar.js : Add "save as pdf" button to save the calendar in a pdf format

javascript - 即使在脚本之前包含 app.js 之后,jquery 也无法正常工作

javascript - Canvas - 如何绘制生长轨迹

javascript - 在正则表达式中转义变量

javascript - 为什么 $.each() 不遍历每个项目?

javascript - 如何识别ajax已提交请求但正在等待响应?

javascript - react : pass Component as prop and use it with additional props

Javascript Office api 在 powerpoint 中插入图像

javascript - 使用 jQuery 将多个 CSS 类组成的 Javascript 数组分配给一个元素