Drawing a grid using CSS

前端 未结 7 2070
青春惊慌失措
青春惊慌失措 2021-02-07 00:20

I\'m looking for a way to draw a grid (i.e. http://www.artlex.com/ArtLex/g/images/grid.gif) inside of a div, using CSS (and JS if necessary). It feels like it should be relative

7条回答
  •  清酒与你
    2021-02-07 01:04

    I know this question has already been answered, but I've done considerable work on this exact problem for a project I was working on, so I thought I would share my findings. Rendering speed was a massive issue for me, and like @YiJiang, I started by appending nodes from inside the loop, but I found that this was not a very performant solution, so I looked into ways to optimise the algorithm.

    Algorithmically speaking, nesting loops causes O(n^2) complexity, which in this case can be avoided by generating the row html once (as it is the same for each row), and then concatenating this string into each row. This results in O(n) complexity, and is by far the most efficient solution I've found.

    function drawGrid(width, height) {
        var grid = '
    ', cell_html = '', i = 0, j = 0; for( ; i < width; i++) { cell_html += '
    '; } for( ; j < height; j++) { grid += '
    ' + cell_html + '
    '; } grid += '
    '; return grid; }

    This creates the basic HTML structure for the grid, which can then be styled appropriately using CSS.

提交回复
热议问题