Installation and use of LayUI

The introduction of LayUI

Layui (homologous: UI) is a front-end UI framework written by its own module specifications, following the writing and organization form of native HTML/CSS/JS, the threshold is very low, and it is ready to use.

Developed by Chinese, 16 years in the factory, the framework of its main provides a lot of nice and easy style, and basic for the box, and the Bootstrap some similar, but the framework has a great benefits is to define the style of the side before and after a lot of interactive interface, such as the paging tables, just on the front end is configured interfaces, the backend is in accordance with the data returned, the interface defined rules The page can be displayed, greatly reducing the development cost of back-end staff.

Website: www.layui.com

Official document: www.layui.com/doc/

The characteristics of LayUI

(1) Layui is a lightweight framework, simple and beautiful. Suitable for developing back-end patterns, it works very well on the server page.

(2) LayUI is a UI framework provided to back-end developers, driven by DOM.

Download and Use

  1. Download the latest version of Layui on the homepage. The directory structure is as follows:

    ├ ─ CSS/ / CSS directory│ │ ─ modules// module CSS directory (generally, if the module is relatively large, we will extract separately, such as the following three :)│ │ ├ ─ laydate │ │ ├ ─ layer │ │ └ ─ layim │ └ ─ layui. The CSS// Core style file├ ─ the font// Font icon directory├ ─ images// Image resources directory (currently only GIF emojis for Layim and editor)│ ─ lay// Module core directory│ └ ─ modules// Each module component│ ─ layui. Js// Base core library└ ─ layui. All. Js// A merge file containing layui.js and all modules
    Copy the code
  2. Once you have layui and have it fully deployed (copied into your project) into your project directory, you just need to import the following two files:

./layui/css/layui.css
./layui/layui.js // Note: if you are using a modular approach, this can be changed to./layui/layui.all.js
Copy the code
  1. Basic getting started page
<! DOCTYPEhtml>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>Start using Layui</title>
  <link rel="stylesheet" href="layui/css/layui.css">
</head>
<body>
 
<! -- Your HTML code -->
 
<script src="layui/layui.js"></script>
<script>
    // Module and callback functions
    // Write it directly in a js file
    layui.use(['layer'.'form'].function(){
      var layer = layui.layer
      ,form = layui.form;

      layer.msg('Hello World');
    });
</script> 
</body>
</html>
Copy the code
  1. You also need to declare the modules and callback functions you want to use. Just refer to the official documentation and choose the effect you want.

    Such as:

    <script>
        // Note: navigation depends on the Element module, otherwise functional operations cannot be performed
        layui.use('element'.function(){
          	var element = layui.element;
    
          	/ /...
        });
    </script>
    Copy the code

The page elements

layout

Layout container

A fixed width

Place the grid in a specific container with class=”layui-container” to fix the width on devices above the small screen and make the column manageable.

<div class="layui-container">
  <div class="layui-row">...</div>
</div>   
Copy the code
Full width

The container width can be left unfixed. Put grids or other elements in a container with class=”layui-fluid” and the width will not be fixed, but 100% fit

<div class="layui-fluid">...</div> 
Copy the code

Grid system

Layui introduces a responsive grid system to enrich web layouts, simplify the coupling of HTML/CSS code, and improve the adaptability of multiple terminals. The container is divided into 12 equal sections, and there are 4*12 CSS permutations preset for four different screens: mobile, tablet, desktop/large.

Raster layout rules
  1. Use layui-row to define rows, such as:

    <div class="layui-row"></div>
    Copy the code
  2. Use a default class like layui-col-md* to define a set of columns within a row. Among them:

    • The variable MD represents the markup under different screens
    • The variable ***** represents the 12 equal fractions (such as 6/12) occupied by the column, with an optional value of 1-12
    • If the sum of the “bisect values” of multiple columns is equal to 12, the row is just full. If it is greater than 12, the extra columns automatically start a new row.
  3. Columns can appear in up to four different combinations at the same time: XS (ultra-small screen, such as mobile phone), SM (small screen, such as tablet), MD (medium desktop screen), and LG (large desktop screen).

  4. Default classes such as layui-col-space5 and layui-col-MD-offset3 can be appended to columns to define the spacing and offsets of columns.

  5. You can fill the column element with any element of your own

Example:

<h3>General layout (medium screen desktop as an example) :</h3>
<div class="layui-row">
	<div class="layui-col-md9" style="background-color: #00F7DE;">Your content is 9/12</div>
	<div class="layui-col-md3" style="background-color: rosybrown;">Your content is 3/12</div>
</div>
Copy the code
Reactive rule

Grid response ability, thanks to the CSS3 Media Queries (Media Queries) strong support, so as to four types of different sizes of the screen, the corresponding adaptation processing.

Ultra-small screen (mobile <768px) Small screen (tablet ≥768px) Medium screen (desktop ≥992px) Large screen (desktop ≥1200px)
.layui-containerThe value of the auto 750px 970px 1170px
tag xs sm md lg
Column corresponding to the class * is 1-12 equal value layui-col-xs* layui-col-sm* layui-col-md* layui-col-lg*
The total number of columns 12 12 12 12
The response behavior Always arrange horizontally in a set proportion Arrange horizontally under the current screen, or stack if the screen size is below the threshold Arrange horizontally under the current screen, or stack if the screen size is below the threshold Arrange horizontally under the current screen, or stack if the screen size is below the threshold
<h3>Different performance of tablet and desktop:</h3>
<div class="layui-row">
    <div class="layui-col-sm6 layui-col-md4"  
         style="background-color: thistle">Tablet p 768 px: 6/12 | desktop client or 992 px: 4/12</div>
</div>

<div class="layui-row">	    
    <div class="layui-col-sm4 layui-col-md6"  
         style="background-color: mediumaquamarine;">Tablet p 768 px: 4/12 | desktop client or 992 px: 6/12</div>
</div>

<div class="layui-row">
    <div class="layui-col-sm12 layui-col-md8" 
         style="background-color: coral">Tablet p 768 px: 12/12 | desktop client or 992 px: 8/12</div>
</div>
Copy the code
The column margins

The spacing between columns is set through the default column spacing class. The left-most column in a row does not have a left margin, and the right-most column does not have a right margin. The column spacing can not only ensure the beautiful layout, but also further ensure the fine degree of the width of the column. Combining common margins of web pages, we preset 12 margins of different sizes, which are as follows:

/* Support all binary intervals between columns 1px to 30px, and singular intervals of 1px, 5px, 15px, 25px */
layui-col-space1 
layui-col-space2 
layui-col-space4 
layui-col-space5 
layui-col-space6 
layui-col-space8 
layui-col-space10 
layui-col-space12 
layui-col-space14 
layui-col-space15 
layui-col-space16 
layui-col-space18 
layui-col-space20 
layui-col-space22 
layui-col-space24 
layui-col-space25 
layui-col-space26 
layui-col-space28 
layui-col-space30
Copy the code

Example:

<h3>The column spacing</h3>
<div class="layui-row layui-col-space10">
    <div class="layui-col-md4" >
        <! Add another div layer to layui-col-md4
        <div style="background-color: #009688;">A third</div>
    </div>
    <div class="layui-col-md4">
        <div style="background-color: burlywood;">A third</div>
    </div>
    <div class="layui-col-md4">
        <div style="background-color: silver;">A third</div>
    </div>
</div>
Copy the code

Note:

Layui-col-space: layui-col-space doesn't work because the padding is used to indent the padding, so it looks like there is no spacing. You can add a div inside to do that. 2. The spacing should not be greater than 30px. If the spacing is greater than 30, column offset is recommended.Copy the code
The column offset

Append a default class like layui-col-mD-offset * to the column to offset it to the right. * indicates the number of columns occupied by the offset. The value can be 1-12. For example, layui-col-mD-offset3 indicates that under “medium desktop screen”, the column is offset to the right by 3 column widths

<h3>The column offset</h3>
<div class="layui-row">
    <div class="layui-col-md4" style="background-color: rosybrown;">
        4/12
    </div>
    <div class="layui-col-md4 layui-col-md-offset4" 
         style="background-color: cornflowerblue;">Offset by 4 columns to the far right</div>
</div>
Copy the code

Note: Column offsets can be set for different screen standards. They are valid for the current screen, and stack when they are below the threshold specified for the desktop screen.

Column nested

Grids can be nested at infinite levels. To complete nesting, insert row elements (layui-col-md*) in column elements (layui-row).

<h3>Column nested</h3>
<div class="layui-row layui-col-space5">
    <div class="layui-col-md5" style="background-color: thistle;">
        <div class="layui-row">
            <div class="layui-col-md3" style="background-color: burlywood;" >Within the column</div>
            <div class="layui-col-md5" style="background-color: indianred;">Within the column</div>
            <div class="layui-col-md4" style="background-color: mediumaquamarine;">Within the column</div>
        </div>
    </div>
</div>
Copy the code

The basic elements

button

usage

Set class=”layui-btn” to any HTML element to create a base button. Define additional button styles by appending a class of the format *layui-btn-{type}*.

<! -- Base button -->
<button type="button" class="layui-btn">A standard button</button>
<a href="http://www.layui.com" class="layui-btn">A jump button</a>
<div class="layui-btn">A button</div>
Copy the code
The theme
The name of the combination
The original class=”layui-btn layui-btn-primary”
The default class=”layui-btn”
joker class=”layui-btn layui-btn-normal”
Warm color class=”layui-btn layui-btn-warm”
warning class=”layui-btn layui-btn-danger”
disable class=”layui-btn layui-btn-disabled”

Example:

<! -- Buttons for different themes -->
<button class="layui-btn">The default button</button>
<button class="layui-btn layui-btn-primary">The original button</button> 
<button class="layui-btn layui-btn-normal">Joker button</button>
<button class="layui-btn layui-btn-warm">Warm color button</button>
<button class="layui-btn layui-btn-danger">The warning button</button>
<button class="layui-btn layui-btn-disabled">Disable the button</button>
Copy the code
size
size combination
large class=”layui-btn layui-btn-lg”
The default class=”layui-btn”
small class=”layui-btn layui-btn-sm”
mini class=”layui-btn layui-btn-xs”
<! -- Different size buttons -->
<button class="layui-btn layui-btn-primary layui-btn-lg">large</button> 
<button class="layui-btn">The default</button>
<button class="layui-btn layui-btn-sm layui-btn-danger">small</button>
<button class="layui-btn layui-btn-xs">mini</button>
Copy the code
Rounded corners

layui-btn-radius

<button class="layui-btn layui-btn-radius">The default button</button>
<button class="layui-btn layui-btn-primary layui-btn-radius">The original button</button> 
<button class="layui-btn layui-btn-normal layui-btn-radius">Joker button</button>
<button class="layui-btn layui-btn-warm layui-btn-radius">Warm color button</button>
<button class="layui-btn layui-btn-danger layui-btn-radius">The warning button</button>
<button class="layui-btn layui-btn-disabled layui-btn-radius">Disable the button</button>
Copy the code
icon
<button type="button" class="layui-btn">
    <i class="layui-icon">&#xe608;</i>add</button>

<button type="button" class="layui-btn layui-btn-sm layui-btn-primary">
    <i class="layui-icon">&#x1002;</i>The refresh</button>
Copy the code

navigation

Navigation generally refers to a set of page guidance channels, mostly in the form of a menu, can be applied to the head and side. Breadcrumbs are simple and support custom delimiters.

Dependency loading module: Element

Implementation steps:

  1. Imported resources

    <link rel="stylesheet" href="layui/css/layui.css">
    <script src="layui/layui.js"></script>
    Copy the code
  2. Dependency loading module

    <script type="text/javascript">
        // Note: navigation depends on the Element module, otherwise functional operations cannot be performed
        layui.use('element'.function(){
            var element = layui.element;
    
        });
    </script>
    Copy the code
  3. Displays navigation for the specified type

Horizontal navigation
<ul class="layui-nav">
	<li class="layui-nav-item"><a href="">The latest activity</a></li>
    <li class="layui-nav-item layui-this"><a href="">product</a></li>
    <li class="layui-nav-item"><a href="">Big data</a></li>
    <li class="layui-nav-item">
        <a href="javascript:;">The solution</a>
        <dl class="layui-nav-child"> <! -- Level 2 menu -->
            <dd><a href="">Mobile module</a></dd>
            <dd><a href="">The background template</a></dd>
            <dd><a href="">Electric business platform</a></dd>
        </dl>
    </li>
    <li class="layui-nav-item"><a href="">community</a></li>
</ul>
Copy the code
Vertical/side navigation
<ul class="layui-nav layui-nav-tree" >
<! <ul class="layui-nav layui-nav-tree layui-nav-side">
  <li class="layui-nav-item layui-nav-itemed">
    <a href="javascript:;">Open by default</a>
    <dl class="layui-nav-child">
      <dd><a href="javascript:;">Option 1</a></dd>
      <dd><a href="javascript:;">Option 2</a></dd>
      <dd><a href="">jump</a></dd>
    </dl>
  </li>
  <li class="layui-nav-item">
    <a href="javascript:;">The solution</a>
    <dl class="layui-nav-child">
      <dd><a href="">Mobile module</a></dd>
      <dd><a href="">The background template</a></dd>
      <dd><a href="">Electric business platform</a></dd>
    </dl>
  </li>
  <li class="layui-nav-item"><a href="">product</a></li>
  <li class="layui-nav-item"><a href="">Big data</a></li>
</ul>
Copy the code

The HTML structure for horizontal, vertical, and side navigation is exactly the same, except that:

Horizontal navigation: layui-nav Vertical navigation needs to be added class: layui-nav-tree Side navigation needs to be added class: layui-nav-tree layui-nav-sideCopy the code
Navigation theme

Add a CSS background class to your navigation to render it a different theme color

<! -- Define a dark green background color for navigation -->
<ul class="layui-nav layui-bg-move" ></ul> 
Copy the code

Other background themes supported by horizontal navigation are: Layui-bg-Cyan (Dark green), Layui-bg-molv (dark green), Layui-bg-blue (bright blue)

Bread crumbs
<span class="layui-breadcrumb">
  <a href="">Home page</a>
  <a href="">International news</a>
  <a href="">The asia-pacific region</a>
  <a><cite>The body of the</cite></a>
</span>
Copy the code

You can also customize the separator by setting the property lay-separator=””. Such as:

<span class="layui-breadcrumb" lay-separator="-">
  <a href="">Home page</a>
  <a href="">International news</a>
  <a href="">The asia-pacific region</a>
  <a><cite>The body of the</cite></a>
</span>
Copy the code

TAB

Navigation menus can be applied to the head and side, support responsive, support deletion of tabs and other functions.

Dependency loading module: Element

Implementation steps
  1. Imported resources

    <link rel="stylesheet" href="layui/css/layui.css">
    <script src="layui/layui.js"></script>
    Copy the code
  2. Dependency loading module

    <script type="text/javascript">
        // Note: The TAB relies on the Element module, otherwise it cannot function
        layui.use('element'.function(){
            var element = layui.element;
    
        });
    </script>
    Copy the code
  3. Load the HTML

    <div class="layui-tab">
      <ul class="layui-tab-title">
        <li class="layui-this">Web site set up</li>
        <li>User management</li>
        <li>To allocate</li>
        <li>Commodity management</li>
        <li>The order management</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">The content of 1</div>
        <div class="layui-tab-item">Content of the 2</div>
        <div class="layui-tab-item">The content of 3</div>
        <div class="layui-tab-item">The content of 4</div>
        <div class="layui-tab-item">The content of 5</div>
      </div>
    </div>
    Copy the code
TAB style
Default style: Layui-Tab For simple style class: layui-tab-brief For card style Class: layui-tab-cardCopy the code
With the delete TAB

You can set the attribute lay-allowClose=”true” to the parent container to allow the Tab Tab to be removed

<div class="layui-tab" lay-allowClose="true">
  <ul class="layui-tab-title">
    <li class="layui-this">Web site set up</li>
    <li>User management</li>
    <li>To allocate</li>
    <li>Commodity management</li>
    <li>The order management</li>
  </ul>
  <div class="layui-tab-content">
    <div class="layui-tab-item layui-show">The content of 1</div>
    <div class="layui-tab-item">Content of the 2</div>
    <div class="layui-tab-item">The content of 3</div>
    <div class="layui-tab-item">The content of 4</div>
    <div class="layui-tab-item">The content of 5</div>
  </div>
</div>
Copy the code

form

Regular use
<table class="layui-table">
  <colgroup>
    <col width="150">
    <col width="200">
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>nickname</th>
      <th>Join time</th>
      <th>The signature</th>
    </tr> 
  </thead>
  <tbody>
    <tr>
      <td>Good heart</td>
      <td>2016-11-29</td>
      <td>Life is like a practice</td>
    </tr>
    <tr>
      <td>Xu luxury,</td>
      <td>2016-11-28</td>
      <td>Among thousands of people, you meet those you've met. Through thousands of years, with the boundlessness of time,</td>
    </tr>
  </tbody>
</table>
Copy the code
Basic properties
The property name Attribute values note
lay-even There is no Used to openinterlacedBackground, which can be used with other properties
Lay-skin =” attribute value” Line (Line border style)

Row (Column border style)

Nob (bezel-less style)
If the default style is used, do not set this attribute
Lay-size =” attribute value” Sm (Small size)

Lg (Large size)
If the default size is used, do not set this attribute

The basic attributes you need are written in the table tag, for example:

<! -- a large table with an interlaced background and a row border style -->
<table class="layui-table" lay-even lay-size="lg" lay-skin="row">
  <colgroup>
    <col width="150">
    <col width="200">
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>nickname</th>
      <th>Join time</th>
      <th>The signature</th>
    </tr> 
  </thead>
  <tbody>
    <tr>
      <td>Good heart</td>
      <td>2016-11-29</td>
      <td>Life is like a practice</td>
    </tr>
    <tr>
      <td>Xu luxury,</td>
      <td>2016-11-28</td>
      <td>Among thousands of people, you meet those you've met. Through thousands of years, with the boundlessness of time,</td>
    </tr>
  </tbody>
</table>
Copy the code

The form

Dependency load module: form

  1. Set class=”layui-form” in a container to identify a block of form elements

    <form class="layui-form" action="">
        
    </form>
    Copy the code
  2. Basic row block structure, which provides responsive support. You can change it to another structure, but you must define class=”layui-form” in the outer container for the form module to work properly.

    <div class="layui-form-item">
      	<label class="layui-form-label">The label area</label>
      	<div class="layui-input-block">The original form element area</div>
    </div>
    Copy the code
Input box
<input type="text" name="title" required lay-verify="required" placeholder="Please enter a title" autocomplete="off" class="layui-input" />  
Copy the code
  • Required: A required field specified by the browser to register

  • Lay-verify: Type of verification required to register the form module

  • Class =”layui-input” : Generic CSS class provided by layui.css

Drop down selection box
<select name="city" lay-verify="">
  <option value="">Please select a city</option>
  <option value="010">Beijing</option>
  <option value="021">Shanghai</option>
  <option value="0571">hangzhou</option>
</select>  
Copy the code
  • attributeselectedDefaults can be set
  • attributedisabledEnable disable, select and option tags are supported
<select name="city" lay-verify="">
  <option value="010">Beijing</option>
  <option value="021" disabled>Shanghai (Disabled)</option>
  <option value="0571" selected>hangzhou</option>
</select>  
Copy the code
  • Can be achieved byoptgroupThe tag groups the select
<select name="quiz">
  <option value="">Please select a</option>
  <optgroup label="City Memory">
    <option value="The first city you worked in.">The first city you worked in?</option>
  </optgroup>
  <optgroup label=Student days>
    <option value="Your job number.">What's your work number?</option>
    <option value="Your favorite teacher">Who is your favorite teacher?</option>
  </optgroup>
</select>
Copy the code
  • By setting the propertieslay-searchTo enable the search match function
<select name="city" lay-verify="" lay-search>
  <option value="010">layer</option>
  <option value="021">form</option>
  <option value="0571" selected>layim</option>
</select>   
Copy the code
Check box
<h2>Default style:</h2>
<input type="checkbox" name="" title="Writing" checked>
<input type="checkbox" name="" title="Stunned"> 
<input type="checkbox" name="" title="Disabled" disabled> 
 
<h2>Original style:</h2>
<input type="checkbox" name="" title="Writing" lay-skin="primary" checked>
<input type="checkbox" name="" title="Stunned" lay-skin="primary"> 
<input type="checkbox" name="" title="Disabled" lay-skin="primary" disabled> 
Copy the code
  • attributetitleCustomizable text (warm tip: If you only want to display check boxes, you can not set title)
  • attributecheckedIt can be selected by default
  • attributelay-skinSettable checkbox style (original style: lay-skin=”primary”)
  • Set *value=”1″* customizable value, otherwise the default on is returned when checked
switch

Turn the checkbox into a switch style by setting lay-skin=”switch”

<input type="checkbox" name="xxx" lay-skin="switch">
<input type="checkbox" name="yyy" lay-skin="switch" lay-text="ON|OFF" checked>
<input type="checkbox" name="zzz" lay-skin="switch" lay-text="Open | close">
<input type="checkbox" name="aaa" lay-skin="switch" disabled>
Copy the code
  • attributecheckedCan be set to on by default
  • attributedisabledOpen the disabled
  • attributelay-textCustomizable switch two states text (two text separated with “|”)
  • Set *value=”1″* customizable value, otherwise the default on is returned when checked
Radio buttons
<input type="radio" name="sex" value="nan" title="Male">
<input type="radio" name="sex" value="nv" title="Female" checked>
<input type="radio" name="sex" value="" title="Neutral" disabled>
Copy the code
  • attributetitleCustomizable text
  • attributedisabledOpen the disabled
  • Set *value=” XXX “* to a customizable value, otherwise the default on is returned
Text field
<textarea name="remark" required lay-verify="required" placeholder="Please enter personal information" class="layui-textarea"></textarea>
Copy the code
  • class=”layui-textarea”: layui.css Generic CSS classes provided by layui.css
Assemble the inline form
<div class="layui-form-item">
    <div class="layui-inline">
        <label class="layui-form-label">The scope of</label>
        <div class="layui-input-inline" style="width: 100px;">
          <input type="text" name="price_min" placeholder="RMB" 
                 autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-mid">-</div>
        <div class="layui-input-inline" style="width: 100px;">
          <input type="text" name="price_max" placeholder="RMB" 
                 autocomplete="off" class="layui-input">
        </div>
    </div>
</div>
Copy the code
  • class=”layui-inline”: Defines the outer line inside
  • class=”layui-input-inline”: Defines the inner line
Ignore beautification

When you add the lay-ignore attribute to a form element, the tag will not be beautified, leaving the system style intact.

<input type="radio" name="sex" value="nan" title="Male" lay-ignore>
Copy the code
Form box style

Set the box style of the form by appending the class of layui-form-Pane.

<form class="layui-form layui-form-pane" action="">
  <! The internal structure is the same, but it is worth noting that the combination of checkboxes/switches/checkboxes in this style requires the addition of the Pane attribute (which would otherwise look awkward), such as: -->
  <div class="layui-form-item" pane>
    <label class="layui-form-label">Radio buttons</label>
    <div class="layui-input-block">
      <input type="radio" name="sex" value="Male" title="Male">
      <input type="radio" name="sex" value="Female" title="Female" checked>
    </div>
  </div>
</form>
Copy the code

Components in the sample

Pop-up layer

Module loading name: Layer, independent version: layer.layui.com

Usage scenarios

Since Layer can be used independently, it can also be used modularized through Layui. So please choose according to your actual needs.

scenario Before using the prepared Call way
1. Use it as an independent component If you just want to use Layer alone, you canlayerDownload component packages from the official website of the independent version. You need to introduce it on your pagejQueryAny version above 1.8 and introducedlayer.js. After importing layer.js with the script tag, use it directly.
2. Modular use of Layui If you are using Layui, you can download the Layui framework from the official website. JQuery and Layer. js are not required, but they arelayui.cssandlayui.js Use (‘layer’, callback)* to load the module
  1. Use Layer as a standalone component

    <! Layer. js -> layer.js -> layer.js -> layer.js
    <script src="layer.js"></script>
    <script>
    	layer.msg('hello'); 
    </script>
    Copy the code
  2. Use Layer in layui

    layui.use('layer'.function(){
      var layer = layui.layer;
      
      layer.msg('hello');
    });
    Copy the code
Basic parameters
  1. Type – Basic layer type

    Type: Number, default: 0 Values that can be passed in are: 0 (info-box, default) 1 (page layer) 2 (iframe layer) 3 (load layer) 4 (Tips layer)Copy the code
  2. Title – title

    Type: String/Array/Boolean, default :' info 'title supports three types of values: if a normal String is passed in, such as title :' I am the title', only the title text will be changed. If you want to customize the style, you can use title: [' text ', 'font-size:18px;'], the second item of the array can write any CSS style; If you don't want to display the title bar, you can use title: false;Copy the code
  3. The content – content

    Type: String/DOM/Array, default: "Content The values that can be passed in are flexible and can be passed in not only plain HTML content, but also the DOM.Copy the code
     /* Information box */
    layer.open({
        type:0.title:"System Message".// Content can be passed in either text or HTML
        content:"Hello"
    });
    
    /* Page layer */
    layer.open({
        type:1.title:"System Message".// Content can be passed in either text or HTML
        content:"
            
    Hello
    "
    }); /* iframe */ layer.open({ type:2.title:"System Message".// Content is a URL. If you don't want iframe to appear in the scrollbar, you can also use content: [' URL ', 'no'] content:"http://www.baidu.com" // content:["http://www.baidu.com",'no'] }); / * * / tips layer layer.open({ type: 4.content: ['content'.'#id'] // The second element of the array is the adsorbed element selector or DOM }); Copy the code
  4. Wide area – high

    Type: String/Array, default: 'auto' By default, layer is width and height adaptive. When defining the width, you can use area: '500px' and the height is still adaptive. Area: ['500px', '300px']Copy the code
  5. Icon – icon

    Note: Information box and load layer private parameters. Type: Number. Default: -1 (info-box) /0 (loading layer) The info-box does not display ICONS by default. When you want to display ICONS, the default layer can pass in 0-6. If it is a load layer, you can pass in 0-2.Copy the code
    // eg1
    layer.alert('Awesome.', {icon: 1});
    // eg2
    layer.msg('No. ', {icon: 5});
    // eg3
    layer.load(1); // Style 1 loading
    Copy the code
  6. The sample

    // eg1
    layer.alert('Nice to meet you 😊', {icon: 6});
    
    // eg2
    layer.msg('Would you like to be my friend? ', {
        time: 0.// Does not automatically close
        btn: ['Of course.'.'Cruel refusal']./ / button
        yes: function(index){ 
            layer.close(index); // Close the current popup
            layer.msg('Hello, new friend! ', {
                icon: 6./ / icon
                btn: ['happy'.'happiness']}); }});// eg3
    layer.msg('This is the usual pop-up layer.');
    
    // eg4
    layer.msg('So sad/(ㄒ o ㄒ) / ~ ~', {icon: 5});
    
    // eg5
    layer.msg('In the middle of... = ̄ω ̄='.function(){
        // Close the operation
        layer.msg('(it's even)? ');
    });
    Copy the code

Date and time selection

Module loading name: Laydate, independent version: www.layui.com/laydate/

LayDate contains a large number of updates, which mainly include: year selector, year selector, date selector, time selector, date and time selector.

Quick to use

Like Layer, you can use layDate in LayUI or directly use layDate independent version. Please choose according to actual requirements.

scenario Before using the prepared Call way
1. Modular use of Layui After downloading Layui, introducelayui.cssandlayui.jsCan be Use (‘laydate’, callback)* to load the module before calling the method
2. Use it as an independent component Go to thelayDateDownload the component package from the official website and import laydate.js Use the direct call method

Used in layui modules

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title>Date and time selection</title>
		<link rel="stylesheet" href="layui/css/layui.css">
	</head>
	<body>
		<div class="layui-inline">
			<input type="text" class="layui-input" id="date1" />
		</div>
	</body>
	<script src="layui/layui.js"></script>
	<script type="text/javascript">
		layui.use('laydate'.function(){
		  var laydate = layui.laydate;
		  
		  // Execute a laydate instance
		  laydate.render({
		    elem: '#date1' // Specify the element
		  });
		});
	</script>
</html>
Copy the code
Basic parameters
  1. Elem – Binding element

    Type: String/DOM. Default: Nothing mandatory for binding elements that perform date rendering. The value is usually a selector, or a DOM objectCopy the code
    laydate.render({ 
      elem: '#test' // or elem: document.getelementByID ('test'), elem: lay('#test'), etc
    });
    Copy the code
  2. Type – Control selection type

    Type: String, default: date Used to provide separate selector types. The possible values are as follows:Copy the code
    Type an optional value The name of the use
    year In the selector Only year list options are available
    month Date selector Only year and month options are available
    date Date picker Optional: year, month, day. Type Specifies the default value. This parameter is optional
    time Time selector Only time, minute and second options are available
    datetime Date and time picker Options: year, month, day, hour, minute, second
    // Year selector
    laydate.render({ 
      elem: '#test'
      ,type: 'year'
    });
     
    // Date selector
    laydate.render({ 
      elem: '#test'
      ,type: 'month'
    });
     
    // Date picker
    laydate.render({ 
      elem: '#test'
      //,type: 'date' // The default value is left blank
    });
     
    // Time selector
    laydate.render({ 
      elem: '#test'
      ,type: 'time'
    });
     
    // Date and time picker
    laydate.render({ 
      elem: '#test'
      ,type: 'datetime'
    });
    Copy the code
  3. Format – Custom format

    Type: String, default: YYYY-MM-DD Specify a date format based on the format and length of the date and time. LayDate supports the following formats:Copy the code
    Format character instructions
    yyyy Year, at least four figures. If there are less than four digits, zeros are added in front
    y Year, unrestricted number of bits, that is, no matter how many bits of the year, before the zero is not added
    MM Month, at least double digits. If there are less than two digits, zero is added in front.
    M Month, one digit allowed.
    dd Date, at least double digits. If there are less than two digits, zero is added in front.
    d Date, one digit allowed.
    HH Hours, at least double digits. If there are less than two digits, zero is added in front.
    H Hours, one digit allowed.
    mm Minutes, at least double digits. If there are less than two digits, zero is added in front.
    m Minutes, one digit allowed.
    ss Seconds, at least double digits. If there are less than two digits, zero is added in front.
    s Number of seconds, one digit allowed.

    A string of date and time can be composed by the above format characters.

    Render ({elem: '#test',format: 'yyyy-mm dd'});Copy the code
  4. Value – Indicates the initial value

    Type: String, default: new Date() Supports passing a Date format character that conforms to the format argument, or new Date().Copy the code
    // Pass a character in format to the initial value
    laydate.render({ 
      elem: '#test'
      ,value: '2018-08-18' // The format parameter must be followed
    });
     
    // Pass the Date object to the initial value
    laydate.render({ 
      elem: '#test'
      ,value: new Date(1534766888000) // The parameter is the timestamp of 2018-08-20 20:08:08
    });
    Copy the code

paging

Module loading name: LayPage

Quick to use

The laypage is very simple to use, pointing to a container that holds pages, getting some initial values from the server, and rendering pages.

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title>paging</title>
		<link rel="stylesheet" href="layui/css/layui.css">
	</head>
	<body>
		<div id="test1"></div>
	</body>
	<script src="layui/layui.js"></script>
	<script type="text/javascript">
		layui.use('laypage'.function(){
		  var laypage = layui.laypage;
		  
		  // Execute a LayPage instance
		  laypage.render({
		    elem: 'test1' // Note that test1 is the ID, not the # sign
		    ,count: 50 // Total data, obtained from the server
		  });
		});
	</script>
</html>
Copy the code
Basic parameters

Basic parameters are set using the core method: layPage.render (options).

Parameter options instructions type The default value
elem Points to a container that holds pages, and the value can be a container ID, a DOM object. 1. Elem: ‘id’Note: # cannot be added here 2. elem: document.getElementById(‘id’) String/Object
count Total data. Usually obtained from the server Number
limit The number of columns displayed per page. Laypage calculates the number of pages using count and limit. Number 10
limits Number of items per page option. If the layout parameter has limit turned on, the select box for the number of items per page appears Array [10, 20, 30, 40, 50]
curr The start page. Generally used for refresh and HASH page hops. Such as:

// Enable records for location.hash

laypage.render({

elem: ‘test1’ ,

count: 500 ,

// Get the start page

curr: location.hash.replace(‘#! fenye=’, ”)

// Customize the hash value

,hash: ‘fenye’

}); `
Number 1
groups The number of consecutive page numbers Number 5
prev Custom “previous page” content, support to pass in plain text and HTML String The previous page
next Customize the content of “Next page”, as above String The next page
first Customize the contents of the home page, as above String 1
last Customize the content of the “back page”, as above String Total page number
layout Custom layout. Possible values are:count(Total entry input area),prev(Area on previous page),page(paging area),next(Next page area),limit(Item option area),refreshPage refresh area. Note: Added to Layui 2.3.0),skip(Quick page hopping area) Array [‘prev’, ‘page’, ‘next’]
theme Customize the theme. Support for incoming:Color valueOr,Any ordinary character. For example: 1. Theme: ‘#c00’ 2. Theme: ‘XXX’ // Will generate class=” layui-layPage-xxx “CSS class to customize the theme String
hash Enable location.hash and customize the hash value. If enabled, urls are automatically appended when paging is triggered:#! Hash value = {curr}With this, you can locate the specified page as soon as the page loads String/Boolean false
Jump – Switch the paging callback

When a page is switched, the function returns two arguments: obj (all options of the current page) and first (whether it is the first time, generally used to determine the initial load).

laypage.render({
    elem: 'page'
    ,count: 100 // Total data, obtained from the server
    ,groups:10 // The number of consecutive page numbers
    ,layout: ['prev'.'page'.'next'.'limit'.'count'] // Custom layout
    ,limits: [5.10.20] The // layout property sets the limit value, and a dropdown box will appear
    ,jump: function(obj, first){
        // obj contains all the parameters of the current page, such as:
        console.log(obj.curr); // Get the current page to request data for the corresponding page from the server.
        console.log(obj.limit); // Get the number of columns per page

        // This is not executed for the first time
        if(! first){//do something}}});Copy the code

The data table

Module load name: table

Quick to use

The easiest way to create an instance of a table is to place an element on the page

table.render()

<! DOCTYPEhtml>
<html>
	<head>
	  <meta charset="utf-8">
	  <title>Table data</title>
	  <link rel="stylesheet" href="layui/css/layui.css">
	</head>
	<body>
		<table id="demo"></table>
	</body>
	
	<script src="layui/layui.js" type="text/javascript" ></script>
	<script type="text/javascript">
		layui.use('table'.function(){
		  var table = layui.table;
		  
		  // First instance
		  table.render({
			elem: '#demo'
			,url: 'user.json' // Data interface
			,cols: [[ / / headers
			  {field: 'id'.title: 'ID'.width:80.sort: true.fixed: 'left'}
			  ,{field: 'username'.title: 'Username'.width:80}
			  ,{field: 'sex'.title: 'gender'.width:80.sort: true}
			  ,{field: 'city'.title: 'city'.width:80} 
			  ,{field: 'sign'.title: 'signature'.width: 177}}]]); });</script>
</html>
Copy the code

Data interface user.json

{
	"code": 0."msg": ""."count": 50."data": [{
			"id": 10000."username": "user-0"."sex": "Female"."city": "City - 0"."sign": "Signature - 0"			
		},
		{
			"id": 10001."username": "user-1"."sex": "Male"."city": "City - 1"."sign": "Signature - 1"
		},
		{
			"id": 10002."username": "user-2"."sex": "Female"."city": "City - 2"."sign": "Signature - 2"
		},
		{
			"id": 10003."username": "user-3"."sex": "Female"."city": "City - 3"."sign": "Signature - 3"
		},
		{
			"id": 10004."username": "user-4"."sex": "Male"."city": "City - 4"."sign": "Signature - 4"}}]Copy the code
Three initial rendering methods
mechanism Applicable scenario
Methods apply colours to a drawing Complete the rendering with the configuration of the JS method (Recommended) Don’t write too much HTML, specify the original elements in JS, and then set the parameters.
Automatic rendering HTML configuration, automatic rendering You don’t have to write a lot of JS to focus on the header of the HTML table
Converting static tables Convert an existing table element Instead of configuring the data interface, specify the table elements in JS and simply add custom attributes to the table header
Methods apply colours to a drawing
  1. The basic parameters are set in the JS code, and the original table tag only needs a selector

    <table id="demo"></table>
    Copy the code
  2. Apply colours to a drawing form

    layui.use('table'.function(){
         var table = layui.table;
    
         // Perform rendering
         table.render({
            elem: '#demo' // Specify the original table element selector (recommendation ID selector)
            ,url: 'user.json' // Data interface
            ,height: 315 // Container height
            ,page:true // Turn on paging
            ,cols: [[  // Set the table header
                {field: 'id'.title: 'ID'}
                ,{field: 'username'.title: 'Username'}
                ,{field: 'sex'.title: 'gender'}}]]); });Copy the code

    The *table.render()* method returns an object: var tableIns = table.render(options), which can be used to “reload” the current table.

Automatic rendering

Configure parameters in a table container and render it automatically from within the table module without writing the initial rendering method.

1) with class=”layui-table

lay-data=””

Tag to set the attribute *lay-data=””* to configure header information

<table class="layui-table" lay-data="{url:'user.json'}">
  <thead>
    <tr>
      <th lay-data="{field:'id'}">ID</th>
      <th lay-data="{field:'username'}">The user name</th>
      <th lay-data="{field:'sex', sort: true}">gender</th>
    </tr>
  </thead>
</table>
Copy the code
Converting static tables

The page already has a table with content, consisting of the original Table tag, and you just need to give it some dynamic elements.

<table lay-filter="demo">
    <thead>
        <tr>
            <th lay-data="{field:'username', width:100}">nickname</th>
            <th lay-data="{field:'experience', width:80, sort:true}">integral</th>
            <th lay-data="{field:'sign'}">The signature</th>
        </tr> 
    </thead>
    <tbody>
        <tr>
            <td>A good heart</td>
            <td>66</td>
            <td>Life is like a practice</td>
        </tr>
    </tbody>
</table>
Copy the code

Execute the JS method used to transform the table

layui.use('table'.function(){
    var table = layui.table;

    // Convert static tables
    table.init('demo', {
        height: 315 // Set the height
        // Support all basic parameters
    }); 

});
Copy the code
Scenarios for using basic parameters
// Table. render({height: 300,url: 'user.json'}); // Scenario 2: The following lay-data is the basic parameter, remember: the value should use single quotation marks<table lay-data="{height:300, url:'user.json'}" lay-filter="demo">...</table>Table. Init ('filter', options); Var tableObj = table.render({}); tableObj.reload(options); // Reload the tableCopy the code
Open the page
<! -- HTML code -->
<table id="demo"></table>
Copy the code
// JS implementation code
layui.use('table'.function(){
    var table = layui.table;

    // Perform rendering
    table.render({
        elem: '#demo' // Specify the original table element selector (recommendation ID selector)
        ,url: 'user.json' // Data interface
        ,height: 315 // Container height
        ,page:true // Turn on paging
        ,cols: [[  // Set the table header
            {field: 'id'.title: 'ID'}
            ,{field: 'username'.title: 'Username'}
            ,{field: 'sex'.title: 'gender'}}]]); });Copy the code
Open the header toolbar
<table id="demo" lay-filter="demo"></table>

<! -- Table Toolbar -->
<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
		<! -- lay-event Binds event names to elements -->
		<button class="layui-btn layui-btn-sm" lay-event="getCheckData">Gets the selected row data</button>
		<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">Get the number of selections</button>
		<button class="layui-btn layui-btn-sm" lay-event="isAll">Verify that all are selected</button>
    </div>
</script>

<! Table header toolbar -->
<script type="text/html" id="barDemo">
	<a class="layui-btn layui-btn-xs" lay-event="edit">The editor</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">delete</a>
</script>
Copy the code
layui.use('table'.function(){
    var table = layui.table;

    // Perform rendering
    table.render({
        elem: '#demo' // Specify the original table element selector (recommendation ID selector)
        ,url: 'user.json' // Data interface
        ,height: 315 // Container height
        ,page:true // Turn on paging
        ,cols: [[  // Set the table header
            {field: 'id'.title: 'ID'}
            ,{field: 'username'.title: 'Username'}
            ,{field: 'sex'.title: 'gender'}
            ,{title:'operation'.toolbar: '#barDemo'} // Bind the table header toolbar]],toolbar: '#toolbarDemo' // Open the header toolbar and bind the left template to it
    });	 
    
    Table. On ('toolbar(demo)', function(obj){}); Note: Demo represents the lay-filter property value */ set on the selector element
    table.on('toolbar(demo)'.function(obj){
        // obj.config.id Id attribute value of the current selector, that is, demo
        // Get the current table selected record object, return an array
        var checkStatus = table.checkStatus(obj.config.id);
        // obj.event Gets the event name of the currently clicked element
        switch(obj.event){ 
            case 'getCheckData':
                // Gets an array of selected records
                var data = checkStatus.data;
                // Parse array data into strings
                layer.alert(JSON.stringify(data));
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('Selected:'+ data.length + 'a');
                break;
            case 'isAll':
                // checkstatus. isAll Checks whether all records are selected
                layer.msg(checkStatus.isAll ? 'all': 'Not all selected');
                break;
                // Customize the header icon on the right of the toolbar - prompt
            case 'LAYTABLE_TIPS':
                layer.alert('This is a custom icon button on the right side of the toolbar.');
                break;
        };
    });
    
    /** * listen for line tool events */
    table.on('tool(demo)'.function(obj){
        // Get information about the current tr operation
        var data = obj.data;
        if(obj.event === 'del') {/ / confirmation box
            layer.confirm("Can you really delete it?".function(index){
                // Delete the specified tr
                obj.del();
                // index Index of the current pop-up layer, which is used to close the pop-up layer
                layer.close(index);
            });
        } else if(obj.event === 'edit') {/ / input box
            layer.prompt({
                // Type 0= textbox 1= password box 2= text field
                formType: 0
                ,value: data.username 
            }, function(value, index){
                // Modifies the value of the specified cell
                // value Indicates the input value
                obj.update({
                    username: value
                });
                // Close the pop-up layerlayer.close(index); }); }}); });Copy the code
Turn on cell editing
<table class="layui-table" lay-data="{url:'user.json', id:'demo'}" lay-filter="demo">
    <thead>
        <tr>
            <th lay-data="{type:'checkbox'}">ID</th>
            <th lay-data="{field:'id', sort: true}">ID</th>
            <th lay-data="{field:'username', sort: true, edit: 'text'}">The user name</th>
            <th lay-data="{field:'sex', edit: 'text'}">gender</th>
            <th lay-data="{field:'city', edit: 'text'}">city</th>
            <th lay-data="{field:'experience', sort: true, edit: 'text'}">integral</th>
        </tr>
    </thead>
</table>
Copy the code
layui.use('table'.function(){
    var table = layui.table;

    // Listen for cell editing
    table.on('edit(demo)'.function(obj){
        var value = obj.value // Get the modified value
        ,data = obj.data // Get all the keys for the row
        ,field = obj.field; // Get the field
        layer.msg('[ID: '+ data.id +'] ' + field + 'Field changed to:'+ value);
    });

});
Copy the code
Reloading of data tables
<div class="demoTable">Search ID:<div class="layui-inline">
        <input class="layui-input" name="id" id="demoReload" autocomplete="off">
    </div>
    <button class="layui-btn" id="searchBtn">search</button>
</div>

<table class="layui-hide" id="demo" lay-filter="demo"></table> 
Copy the code
layui.use('table'.function(){
    var table = layui.table;
    var $ = layui.jquery; // Get the jquery object

    // Perform rendering
    table.render({
        elem: '#demo' // Specify the original table element selector (recommendation ID selector)
        ,url: 'user.json' // Data interface
        ,page:true // Turn on paging
        ,cols: [[  // Set the table header
            {type: 'checkbox'.fixed: 'left'} // Set the check box, {field: 'id'.title: 'ID'}
            ,{field: 'username'.title: 'Username'}
            ,{field: 'sex'.title: 'gender'}}]]);// Bind events to the specified element
    $(document).on('click'.'#searchBtn'.function(data) {
        // Get the search box object
        var demoReload = $('#demoReload');
        table.reload('demo', {
            where: { // Set additional parameters for the asynchronous data interface
                id: demoReload.val()
            }
            ,page: {
                // Make the conditional query start from the first page, if not, start from the current page, the data before this page will not be included in the conditional filter
                curr: 1 // Start from page 1 again}});// Only reload data
    });
});
Copy the code