0

我正在创建一个移动优先响应式网站,其中包含一些在某些断点处启动的自定义 jquery 插件。

首先,代码片段,然后解释问题......

CSS:

@media (min-width: 20em) {
  html:after {
    content: "320";
     } }
@media (min-width: 25em) {
  html:after {
    content: "400";
     } }
@media (min-width: 30em) {
  html:after {
    content: "480";
     } }

全球JS

var FOO = {
 mq: function() {
   return  parseInt(window.getComputedStyle(document.documentElement,':after').getPropertyValue('content').replace(/['"]/g,''),10);                     
 }
}

jQuery插件1

this.init = function()
{
 $(window).on("load resize orientationchange", function() {
   if(FOO.mq() >= 480) {
      DO SOMETHING
   }
});
};

查询插件 2

this.init = function()
{
 $(window).on("load resize orientationchange", function() {
   if(FOO.mq() >= 560) {
      DO SOMETHING ELSE
   }
});
};

现在将 FOO.mq() 放入 jquery 插件的问题在于,它将为找到的每个 DOM 对象触发 FOO.mq() 函数(例如,如果插件对 10 个图像执行某些操作,它将触发 FF.mq( ) 10 次) 真的不需要,因为我们只需要检查一次。

我尝试将调整大小/返回值放在全局对象中,但它似乎永远不会工作并且被 jquery 插件拾取。

任何指针将不胜感激。

谢谢

4

2 回答 2

1

假设此计算值仅在文档加载或窗口更改布局时发生变化:

var FOO = FOO || {};      // create global namespace obj, if required
$(function() {
    var mq;               // scoped variable

    // catch events that might change the @media CSS rules
    $(window).on("load resize orientationchange", function() {
        mq = parseInt(window.getComputedStyle(document.documentElement,':after').getPropertyValue('content').replace(/['"]/g,''),10);
    });

    FOO.mq = function() { // function that just returns the scoped variable
        return mq;
    }
});
于 2013-04-30T10:48:16.603 回答
0

尝试使用超时:

this.init = function () {
    var timeout;
    $(window).on("load resize orientationchange", function () {
        clearTimeout(timeout);
        timeout = setTimeout(function(){
           if (FOO.mq() >= 480) {
               DO SOMETHING
           }
        },15);//even 0 should be enough
    });
};
于 2013-04-30T10:02:28.457 回答