search
HomeWeb Front-endJS TutorialIntroduction to Grid, a tool for quickly generating various grid layouts using JS

In the past two days, I have learned about the grid layout of CSS and found that it is indeed very useful. After reading a few blogs and understanding some of its common properties, you can quickly generate a grid layout. Compared with traditional float, positioning, etc., it is more systematic and standardized. Grid.js is a module that uses JavaScript to dynamically create regular grid layout and irregular grid layout. FE can create a Grid instance through new Grird(option), and the UI of the instance will be presented as a css grid layout. Some hacks are needed.

Although the grid layout is already very good, some front-end engineers prefer to complete their work by dynamically creating p and using js to add styles to p.

Also out of the need to use JavaScript to dynamically generate grid layout, the small tool Grid.js was born.

Renderings

Let’s take a look at some renderings generated using Grid.js.
The sizes of the parent containers of the following four renderings are all 600*600 pixels.

The first one is a 4X4 grid, 3 of which are non-atomic size (1X1), namely 2X2, 2X2, 2X1.
Introduction to Grid, a tool for quickly generating various grid layouts using JS

The second picture is a 5X5 regular grid. The so-called regular grid means that all sub-elements are 1X1 in size.
Introduction to Grid, a tool for quickly generating various grid layouts using JS

The third picture is a 6X5 grid with 5 non-atomic sized grids.
Introduction to Grid, a tool for quickly generating various grid layouts using JS

The fourth picture is a 7X7 grid with 4 non-atomic sized grids.
Introduction to Grid, a tool for quickly generating various grid layouts using JS

Grid.js uses

Grid.js is completed using es6 class syntax, so the usage is very simple.
You can generate a grid instance through new Grid(option). As for the 5X5 grid generated in the second picture of the rendering, its code is:

<span style="font-size: 14px;">let grid = new Grid({<br>            container:document.getElementsByClassName('grid')[0],// 必须项<br>            colCount:5,<br>            rowCount:5,<br>            width:600,<br>            height:600,<br>        });<br></span>

If you want to set a different style for each grid, use the external API method setGridStyleByIndex(); Similarly, taking the 5X5 grid in the rendering, the five diagonal grids are used to set the background style. They are completed through the following code:

<span style="font-size: 14px;">grid.setGridStyleByIndex(0, {"background": "red"});<br>grid.setGridStyleByIndex(6, {"background": "green"});<br>grid.setGridStyleByIndex(12, {"background": "yellow"});<br>grid.setGridStyleByIndex(18, {"background": "blue"});<br>grid.setGridStyleByIndex(24, {"background": "orange"});<br></span>

Another question is how to get the reference of each sub-element (small grid)? Through the external API method getGrid(n).
Another question is how to get the references of all sub-elements (small grids)? Through the external API method getGrids().

<span style="font-size: 14px;">let grids = grid.getGrids();<br>for(let i = 0; i     grids[i].innerHTML = i + 1;<br>}<br></span>

The above code takes the references of all the small grids and then fills the grids with text content. In the example, the text content of each small grid is the index + 1 of each small grid in the p list.

Grid.js API

Considering the core requirements, there are two points. One is relatively simple (at least the same as using css directly). Convenience) to generate a grid layout. The second is to get the reference of each grid after generating the grid layout and add content to the grid. So we mainly talk about these two aspects.

Pass parameters to generate grid instances

How to generate different, regular, and irregular grid instances mainly depends on new Grid( option), the parameters that can be passed include the following.

##Height of parent containerpCountnumberHow many actual grids are theregridAreaArrayThe placeholder representation of those non-1X1 grids
Name Type Introduction
container ##htmlDomElement Parent container, required item
rowCount number Number of grid rows
colCount number Number of grid columns
width number、% Parent container width
height number、%

Instructions on pCount and gridArea arrays: These two parameters are used to generate irregular grid layout, so they are the key to this module. Otherwise, you can only use this module to generate n*m ​​regular grids.

Let’s take the 4X4 grid in the first rendering as an example. Originally, if the three grids 1, 2, and 3 had cross-row and cross-column behavior, there would be no need to pass pCount. , there is no need to pass gridArea, the module will generate 4X4=16 identical grids for you. However, due to the existence of these three larger grids, this parent container cannot accommodate 16 child elements. Therefore, what is the pCount you pass?

is when there are non-1X1 child grids. The number of subgrids when the container is exactly full, so it is 9.. Generally, when you get the design drawing, you already know the layout, and the number of sub-grids is easy to calculate (because the actual scene does not need to create dozens of trivial grids multiplied by dozens).

For these three non-1X1 sub-grids, we need to pass an array for each of them to indicate which row of the parent grid this sub-grid starts. Which column to start in, how many rows to span, and how many columns to span. That is, each non-1X1 subgrid must pass an array with a length of 4. Then put these arrays into an outsourcing array. This outsourcing array is gridArea.

For rendering 1, gridArea = [[1,1,2,2],[2,3,2,2],[4,1,1,2]] .

The entire 4X4 grid has 3 non-1X1 size subgrids. [1,1,2,2] means that there is a sub-grid starting from the first row and first column in this 4X4 grid, with a value of 2 across rows and columns.

API interface

Currently exposed API

NameParameter typeIntroductionsetGridStyleByIndex(n,style)number,objSet the small grid style, the first parameter is the small grid index; style is an object, for example style={"color":"red"}getGrids()None Get all subgrid p referencesgetGrid(n)numberGet a certain subgrid
Related recommendations:


Sample code of CSS grid layout

Detailed explanation of the use of ui-grid grid layout in jQuery mobile page development_jquery

Grid layout example detailed explanation

The above is the detailed content of Introduction to Grid, a tool for quickly generating various grid layouts using JS. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)