jQuery 响应功能在屏幕尺寸改变之前无法使用

jQuery responsive function not working until screen size changes

我正在使用下面的 jQuery 根据用户的屏幕尺寸在我的页面上移动一些元素。

我遇到的问题是代码工作正常,但只有当您手动调整屏幕大小时,即使只有 1px,它也会触发,但从不加载文档时?

有没有我哪里出错的想法?​​

jQuery(document).ready(function () {

    /*
     * windowSize
     * call this function to get windowSize any time
    */

    function windowSize() {
        windowHeight = window.innerHeight ? window.innerHeight : 
        $(window).height();
        windowWidth = window.innerWidth ? window.innerWidth : $(window).width();      
    }

    //Init Function of init it wherever you like...
    windowSize();

    // For example, get window size on window resize
    $(window).resize(function() {
        windowSize();
        //console.log("width is :", windowWidth, "Height is :", windowHeight);
        if (windowWidth > 1029) {
            $("#single-related").appendTo("#product-team-shop");
        } 
    });        
});

这是因为 window 调整大小事件仅在 window 调整大小时触发。

如果你想执行一个 onLoad 函数,你可以这样做:

jQuery(document).ready(function () {

  // Function executed once the document is loaded
  windowSize();

  // The function windowSize will execute when the window gets resized
  $(window).resize(function() {
    windowSize();
  });   

  function windowSize() {
    windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
    windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
    // This will make sure it checks the window size once the document is loaded but also whenever a resizeEvent occurs     
    checkWindowWidth();
  }

  function checkWindowWidth() {
    if (windowWidth > 1029) {
        $("#single-related").appendTo("#product-team-shop");
        console.log('resized width greater than 1029');
    }
  }
});

我已将追加代码和控制台代码放在名为 checkWindowWidth 的函数中。每当调用 windowSize 函数以及发生调整大小事件时,我都会执行它。

因为 windowSize 函数在文档加载后被调用,这意味着 checkWindowWidth 函数在文档加载时和 window 调整大小时被触发。