matchMedia调用函数两次 [英] matchMedia calls functions twice

查看:206
本文介绍了matchMedia调用函数两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在移动设备上使用某个功能(在此示例中少于700px),并在大型设备上使用另一个功能。我以下列方式使用matchMedia:

I am trying to use a function on mobile devices (less than 700px in this example) and another function on large devices. I use matchMedia in the following way:

var mql = window.matchMedia("(min-width: 700px)");
mql.addListener(handleResize);
handleResize(mql);
function handleResize(mql) {
    if (mql.matches) {      
    $(".button").on("click", function(){
        $(".hidden").slideToggle();
    })                 
  } else {  
    $(".button").on("click", function(){
        $(".hidden").fadeToggle();
    })   
  }
}

首先,代码按预期运行,当我调整窗口大小时会出现问题。例如,如果窗口首先加载到700px以下,然后调整大小超过700px,则按钮首先闪烁,然后滑动,反之亦然。我想要实现的目标是只在大屏幕上调用幻灯片,只在小屏幕上淡出。非常感谢任何帮助。

At first, the code behaves as expected, the problem occurs when I resize the window. For instance, if the window first loads under 700px and then is resized to more than 700px, the button fires fade first, then slide and vice versa. What I want to achieve off course is calling only slide on large sreens and only fade on small screens. Any help is greatly appreciated.

干杯!

推荐答案

问题是每次 handleResize 回调触发时,它会向该按钮附加另一个单击事件。为防止附加大量事件,您必须先使用 off()将其删除。

The problem is that every time the handleResize callback fires, it attaches another click event to the button. To prevent attaching a ton of events, you have to first remove it with off().

这是一个完成你想要的例子:

Here is an example that accomplishes what you wanted:

var $hidden = $('.hidden');
var $btn = $('button');
var mql = window.matchMedia("(min-width: 700px)");

function bindSlide() {
  // Using `off()` is required in order not to end up attaching a lot of callbacks
  $btn.off("click.mql").on("click.mql", function() {
    $hidden.stop().slideToggle();
  }); 
}

function bindFade() {
  $btn.off("click.mql").on("click.mql", function() {
    $hidden.stop().fadeToggle();
  }); 
}

function handleScreen(mql) {
  if (mql.matches) {       
    bindSlide();
  } else {
    bindFade();
  }
}

// Handle media query 'change' event
mql.addListener(handleScreen);
handleScreen(mql);

请注意 window.matchMedia isn'所有浏览器都支持。对于本身不支持matchMedia的浏览器,您可以使用polyfill: https://github.com/paulirish/ matchMedia.js

Please note that window.matchMedia isn't supported by all Browsers. For Browsers that don't support matchMedia natively you can use a polyfill: https://github.com/paulirish/matchMedia.js

实例: http:// jsfiddle.net/rhkLng9o

这篇关于matchMedia调用函数两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆