调整大小后,Divs 的数量适合浏览器 window

Divs' number fit to browser window with resizing

这是这段代码: https://jsfiddle.net/qw3fp7sk/

该代码在页面上显示相同大小的 div,并且 div 的数量适合页面的实际大小,没有滚动。

我想在更改浏览器的 window 大小时即时更改页面上的 div 数量。 div 的编号必须适合 window 而无需滚动。

目前,仅当我单击 jsfiddle 的 运行 按钮时,div 的编号才会在页面调整后发生变化。

这是代码片段,它不起作用:

   $(window).on('resize', function() {

        // define global width and height variables
        var width = new jqUpdateSize().width;
        var height = new jqUpdateSize().height;

        // define div numbers to actual screen width (on one line)
        var lastw = '';
        for (var i = divwidthCalc; i < width; i+=divwidthCalc) {
        lastw++;
        }

        // define div numbers to actual screen height (on one row)
        var lasth = '';
        for (var i = divheightCalc; i < height; i+=divheightCalc) {
        lasth++;
        }

        // define the max div numbers
        var numDivMaxOnPage = lastw * lasth;

        //alert(numDivMaxOnPage);

        setGridDimensions(numDivMaxOnPage);


    });

提前感谢您的帮助。

问题出在您的 numDivMaxOnPage 变量上。它定义了两次。

// divs w, h, margin
    // you can modify these datas
    var divborder = 5;
    var divwidth = 100;
    var divheight = 100;
    // calculating the values to define max div on lines and on rows
    var divwidthCalc = divwidth+(divborder*2);
    var divheightCalc = divheight+(divborder*2);

    var numDivMaxOnPage = null;


  function setGridDimensions(n) {
        var html ='';
        for (var i = 0; i < numDivMaxOnPage; i++) {
        html += '<div class="row">' + (i+1);
        html += '</div>';
        }
        $(document.body).html(html);

         // div size css
        $('.row').css({'width': divwidth + 'px', 'height' : divheight + 'px', 'border-width' : divborder + 'px'});
    };

    calculate();

    // not working function...
    $(window).on('resize', function() {

        calculate();


    });

  function calculate() {
        var width = $(window).width();
        var height = $(window).height();

        // define div numbers to actual screen width (on one line)
        var lastw = '';
        for (var i = divwidthCalc; i < width; i+=divwidthCalc) {
        lastw++;
        }

        // define div numbers to actual screen height (on one row)
        var lasth = '';
        for (var i = divheightCalc; i < height; i+=divheightCalc) {
        lasth++;
        }

        // define the max div numbers
        numDivMaxOnPage = lastw * lasth;

    // run function
        setGridDimensions(numDivMaxOnPage);

  }

https://jsfiddle.net/ne05rftp/1/