【问题标题】:Call a JS function at a set window width以设定的窗口宽度调用 JS 函数
【发布时间】:2015-08-10 15:02:40
【问题描述】:

我想调用一个 JavaScript 函数,该函数在每次加载时以及每次调整屏幕大小时检查窗口的宽度。这样做的原因是我不希望在屏幕尺寸太小时使用函数,例如手机尺寸。

这个可以吗?

我试过做这样的事情

window.onload = function () {
    if (window.onload.innerWidth > 991 || window.onresize.innerWidth > 991) {
        var maxHeight = 0;
        setTimeout(function () {
            maxHeight = 0;
            $(".menu> div").each(function () {
                var thisHeight = parseInt($(this).css("height").toString().replace("px", ""));
                if (thisHeight > maxHeight) {
                    maxHeight = thisHeight;
                }
            });
            $(".menu> div").css("height", maxHeight.toString() + "px");
            $(".menu").sortable({
                handle: "h3",
                placeholder: {
                    element: function (currentItem) {
                        return $("<div class='col-md-4 placeholderBlock' style='height:" + (maxHeight).toString() + "px; '></div>")[0];
                    },
                    update: function (container, p) {
                        return;
                    }
                }
            });
            $(".menu").disableSelection();

            $(".widget").each(function () {
                $(this).click(function () {
                    enableDisableWidget($(this));
                });
            });

            setInterval(function () {
                var menu= { items: [] };
                $(".menu> div").each(function () {
                    menu.items.push(
                        {
                            classes: "." + $(this).attr("class").replace(/\ /g, ' ')
                        }
                    );
                });
                $(".hiddenField_dashboardLayout").val(JSON.stringify(dashboardItems));
            }, 500);
        }, 2000);
    }
}

【问题讨论】:

  • 您想要一个纯 JavaScript 答案还是使用 jQuery 的答案?
  • @BDawg 两者都可以。我尝试使用下面的一些建议,但它们似乎只工作一次。例如,如果我多次调整页面大小,该功能似乎没有触发
  • 这是一个有趣的问题。请问您使用哪个浏览器有困难?另外,this 在该浏览器上是否适合您?每次调用 yourFunction 时它应该加 1

标签: javascript


【解决方案1】:

你可以有一个函数检查 window.innerWidth 是否大于你的限制大小

var limitFunc = function(){
    if (window.innerWidth>999){
       /*your functions for big screen*/
     console.log('bigScreen')
    }
};

您在窗口调整大小和加载事件时触发限制功能

window.addEventListener("resize", limitFunc);
window.addEventListener("onload", limitFunc);

fiddle

【讨论】:

    【解决方案2】:

    window.onload.innerWidth &gt; 991 || window.onresize.innerWidth

    那是行不通的。它们都是没有称为 innerWidth 的属性的事件属性。

    您需要将其更改为:

    document.body.offsetWidthwindow.innerWidthdocument.documentElement.clientWidth

    onload 将在页面加载时执行您想要的操作。

    添加另一个名为onresize的事件

    $(window).on("resize", function(){});
    

    您也可以为此使用 CSS:

    @media only screen and (min-width: 991px) { ... }
    

    大括号之间的css规则只会在屏幕大于991像素时应用。

    【讨论】:

      【解决方案3】:

      这应该适合你:

      function yourFunction() {
          if (window.innerWidth >= 992) {
              //TODO: Your code here
          }
      }
      
      // Set both event handlers to same function
      window.onload = window.onresize = yourFunction;
      

      顺便说一句,线……

      if (window.onload.innerWidth > 991 || window.onresize.innerWidth > 991)
      

      ...不起作用,因为 window.onloadwindow.onresize 是函数。

      【讨论】:

        【解决方案4】:

        您可以使用 jQuery 为 resize 事件添加监听器:

        $(window).on("resize", function(){
            console.log("resized");
        });
        

        或纯 javascript 方式,由 answer 提供。

        var addEvent = function(object, type, callback) {
            if (object == null || typeof(object) == 'undefined') return;
            if (object.addEventListener) {
                object.addEventListener(type, callback, false);
            } else if (object.attachEvent) {
                object.attachEvent("on" + type, callback);
            } else {
                object["on"+type] = callback;
            }
        };
        
        addEvent(window, "resize", function(event) {
          console.log('resized');
        });
        

        我写了这段代码,希望能满足您的需求。纯javascript:

        //this function will return true if the window is too small
        var isTooSmall = function(w, h){
            console.log(w + " " + h); //just to check width and height
            var min_w = 200; //set these to what you wish
            var min_h = 200;
            if(w < min_w || h < min_h){
                return true;
            }
            else return false;
        };
        
        //this function will allow us to bind listeners given an object and its event.
        //Check the linked stackoverflow answer for more explanation
        var addEvent = function(object, type, callback) {
            if (object == null || typeof(object) == 'undefined') return;
            if (object.addEventListener) {
                object.addEventListener(type, callback, false);
            } else if (object.attachEvent) {
                object.attachEvent("on" + type, callback);
            } else {
                object["on"+type] = callback;
            }
        };
        
        //resize listener
        addEvent(window, "resize", function(event) {
            console.log(isTooSmall(window.innerWidth, window.innerHeight));
        
        });
        
        //onload listener
        window.onload = function () { 
            console.log(isTooSmall(window.innerWidth, window.innerHeight));
        }
        

        这是一个jsfiddle 来查看它的实际应用。

        【讨论】:

        • 你能补充一些解释吗?
        • 是的,我马上用注释更新代码!
        【解决方案5】:

        function myFunction() {
            var w = window.outerWidth;
            //var h = window.outerHeight;
            
            if (w > 991) {
              document.getElementById("p").innerHTML = "big " + w;
            } else {
              document.getElementById("p").innerHTML = "small " + w;
            }
        }
        <body onresize="myFunction()" onload="myFunction()">
        <p id="p"><p>
        </body>

        【讨论】:

          猜你喜欢
          • 2016-07-08
          • 1970-01-01
          • 2011-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-25
          相关资源
          最近更新 更多