在div元素中的HTML / JS中绘制矩形网格的最简单方法是什么?

时间:2016-05-10 11:06:51

标签: javascript html css

我正在尝试创建一个简单的用户界面,允许用户将数独游戏堆叠在一起。到目前为止,界面的粗略外观是这样的。

enter image description here

我现在想要实现允许我在右边的白色矩形(div)内生成数独网格的逻辑。例如,如果用户输入cols 4和row 4,则必须生成一个看起来像这样的4x4矩形(当然要小一些:)):

enter image description here

一旦这样的网格在该广场内,我想让用户将其拖到左边的灰色div区域。但是当你这样做时,白色矩形内的那个应该保留(所以基本上当你拖动那个方块时,你将它的一个克隆拖到左侧 - 这样你就可以从白色方块中抓取额外的网格并堆叠尽可能多的他们如你所愿在左边。

最好在灰色区域上放置一个大网格,以便您可以对齐拖动的方块(不需要剪裁)。欢迎提出所有建议!

提前致谢:)

1 个答案:

答案 0 :(得分:0)

我在jQuery中写了这篇文章。它可能需要根据您的需求进行调整,但实质上它会创建任意大小的网格。

// HTML elements

var game_element = $('.game'); // Main game html
var grid_parent = $('.grid');
var grid_section = $('.grid_section')
var grid_parent_html = '<div class="grid"></div>';
var grid_section_html = 'grid_section';

/**
* CREATE THE GRID. Function loops through section count and appends the
* neccessary components with correct widths in relation to the screen size.
**/

function create_grid(horizontal,vertical){

    // Set the height and widths of the grid sections
    p_width = 100 / horizontal + '%';
    p_height = 100 / vertical + '%';

    // Loop through required sections and append to our main grid
    for(i = 0; i < horizontal * vertical; i++){
        grid_parent.append(
            '<div style="width:' + 
            p_width + ';height:' + p_height + '" class="' + 
            grid_section_html + '"></div>'
        );
    }
    section_total = horizontal * vertical;
}


create_grid(4,4);

和一点CSS

*{
    box-sizing:border-box;
}

body{
    height:100vh;
    margin:0;
    padding:0;
    .grid_holder{
        padding:50px;
        height:100vh;
        .grid{
            height:100%;
            &_section{
                float:left;
                box-shadow:0px 0px 0px 1px black inset;
                padding:10px;
            }
        }
    }
}

您可以在此处查看一个有效的示例http://codepen.io/jcoulterdesign/pen/a4134449d800430fafedce13122f207a