2

See this fiddle.

enquire.register("screen and (max-width: 640px)", {
    match: function () {
        $("body").css("background","red");
    },
    unmatch: function () {
        $("body").css("background","blue");
    }
});

when the browser window is 640px or less on load then the background-color will be set to red. (i.e. the match event is called). However, when the window is wider than 640px on load, nothing happens, i.e. the unmatch event is not called. Why not? And is there a way to force the unmatch event to fire if there is no match with the condition?

Basically what I want is that enquire behaves as an if-else statement that is immediatelly called.

4

2 回答 2

6

当我设计 enquire.js 时,它打算与移动优先的 RWD 一起使用。因此,它假设您正在采用渐进式增强方法。也就是说,当查询匹配时调用 match,并且仅当 match 已经发生一次(并且查询不再匹配)时才调用 unmatch。这可能看起来很奇怪,但常见的用例是“当这个查询匹配时做某事,当它不再匹配时撤消它”。一个示例可能是将元素转换为大屏幕上的选项卡区域,否则返回堆叠元素:

enquire.register(desktopMediaQuery, {
  match : function() { 
    makeTabs(someElement);
  },
  unmatch : function() {
    makeStacked(someElement);
  }
};

如果 unmatch 最初被调用,当查询不匹配时,那么你必须在你的 unmatch 回调中放入逻辑来检查匹配是否已经发生(或者更糟,但是这样的逻辑在makeStacked)。

如果我们要严格遵循渐进增强,在您的示例中,我将在 CSS 中默认使用蓝色背景,并在 match 中添加一个类,并在 unmatch 中删除该类:

enquire.register("screen and (max-width: 640px)", {
    match: function () {
        $("body").addClass("red-bg");
    },
    unmatch: function () {
        $("body").removeClass("red-bg");
    }
});

尽管我假设您的示例是您实际想要的简化版本。所以另一种方法是使用设置回调来掩盖默认情况:

enquire.register("(max-width: 640px)", {
    setup : function() {
        $("body").css("background","blue");
    },
    match : function() {
        $("body").css("background","red");
    },
    unmatch : function() {
        $("body").css("background","blue");
    }
});

如果这更适合您需要做的事情,您也可以使用两个媒体查询。我认为这比使用上述设置更能传达意图。

enquire.register("(max-width: 640px)", {
    match : function() {
        $("body").css("background","red");
    }
})
.register("(min-width: 641px)", {
    match : function() {
        $("body").css("background","blue");
    }
});

这是一个演示这两种方法的小提琴:http: //jsfiddle.net/7Pd3m/

于 2014-07-07T19:14:53.777 回答
0

Inquire js 在 register 函数内部提供了一个名为setup的方法,该方法在调用register 处理程序时触发一次(没有检测到任何媒体查询)。因此,您可以像这样扩展代码以包含它:

enquire.register("screen and (max-width: 640px)", {
    setup: function() {
     // do stuff here as soon as register is called.
    },
    match: function () {
        $("body").css("background","red");
    },
    unmatch: function () {
        $("body").css("background","blue");
    }
});

(引用自他们的文档http://wicky.nillia.ms/enquire.js/#quick-start

于 2015-03-18T16:56:42.973 回答