繁体   English   中英

在调整大小时将全局javascript变量传递到jquery插件中

[英]passing a global javascript variable into jquery plugins on resize

我正在创建一个具有一些自定义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
   }
});
};

JQUERY插件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插件获取。

任何指针将不胜感激。

谢谢

假定此计算值仅在文档加载时更改,或者窗口更改布局时:

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;
    }
});

尝试使用超时:

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
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM