Source: making a qualified primary front-end engineers need to acquire module notes | o stars ✨ | give a ❤ ️ attention, ❤ ️ thumb up, ❤ ️ encourages the author

Hello, everyone. I’m Nezha, the demon king. Nice to meet you

Nezha’s Life creed: If you learn something in love will have a strong motivation support.

Learn programming every day, so that you can update a step from your dream, thank you for every programmer who loves programming, no matter how strange the knowledge is, together with me, let the wandering heart settle down, go all the way, come on, 2021 come on! Welcome to follow and add me vx: Xiaoda0423, welcome to like, collect and comment

Don’t be afraid to dream, but don’t just dream. Be a doer, not a talker.

preface

If this post helped you, follow it at ❤️, like it at ❤️, and encourage the author at ❤️. Are you ready for the challenge? Article public number debut, attention programmer Doraemon first time to obtain the latest article

❤ ️ cartridge ❤ ️ ~

The Web module

Basic HTML structure

  1. htmlLabel is made<>Surround the key words.
  2. htmlTags usually come in pairs, with an beginning tag and an end tag.
  3. Some labels have no closing tags and are single labels. Single labels must be used/At the end.
  4. All the content of the page is therehtmlTag.
  5. htmlA tag is divided into three parts: tag name, tag content, and tag attributes.
  6. htmlTags have semantics, and the content of the tag can be judged by the tag name. The function of semantics is to make the structure of web pages clearer, easier to be included by search engines, and easier for screen readers to read the content of web pages.
  7. The content of a tag is the content inside a pair of tags.
  8. The contents of a tag can be other tags.

Tag attributes

  1. classAttribute: The class name used to define the element
  2. idAttribute: Used to specify the uniqueness of an elementid, the value of the property is in the entirehtmlUniqueness in the document
  3. styleProperty: specifies the inline style of an element. Using this property overrides any global style Settings
  4. titleAttribute: Additional information used to specify an element
  5. accesskeyProperty: Specifies the shortcut key that activates the element
  6. tabindexAttribute: Used to specify where the element istabOrder under the key
  7. dirAttributes: Used to specify the text orientation of the content in an element. Attributes have onlyltrorrtlTwo kinds of
  8. langAttribute: The language used to specify the content of an element

Event attributes

  1. windowWindow event,onloadIs triggered after the page has finished loading,onunloadOccurs when the user leaves the page (click to jump, reload the page, close the browser window, etc.)
  2. formForm events,onblurWhen the element loses focus,onchangeWhen the element’s value is changed,onfocusWhen the element gets focus,onresetIs triggered when the reset button in the form is clicked,onselectIs triggered when the element text is selected,onsubmitTriggered when the form is submitted
  3. keyboardKeyboard events,onkeydownIs triggered when the user presses a key,onkeypressIs triggered when the user presses the key. This property does not apply to all keys.alt,ctrl,shift,esc
  4. mouseMouse event,onclickIs triggered when a mouse click occurs on an element,onblclickIs triggered when a double mouse click occurs on an element,onmousedownIs triggered when the mouse button is pressed on the element,onmousemoveIs fired when the mouse pointer moves over the element,onmouseoutWhen the element pointer moves out of the element,onmouseupTriggered when the mouse button is released on the element.MediaMedia events,onabortIs triggered when exiting,onwaitingTriggered when the media has stopped playing but intends to continue playing.

Text labels

  1. Paragraph tags<p></p>Paragraph tags are used to describe a piece of text
  2. The title tag<hx></hx>Title tags are used to describe a title. There are six levels of title tags.<h1></h1>Tags typically appear only once per page
  3. Emphasize statement tags,<em></em>Used to emphasize the importance of certain words
  4. More emphasis on labels,<strong></strong>and<em>The tag is used to emphasize text, but to a greater degree
  5. No semantic tags<span></span>, the tag has no semantics
  6. Short text reference tags<q></q>“, a quote of short text
  7. Long text reference tags<blockquote></blockquote>To define long text references
  8. Wrap the label<br/>

Multimedia label

  1. Link tags,<a></a>
  2. Picture tag,<img/>
  3. Video tag,<video></video>
  4. Audio label,<audio></audio>

The list of

  1. Unordered list tag,ul,li.<ul></ul>A list defines an unordered list,<li></li>It means you don’t need every element in the list
  2. Ordered list,ol,li
  3. Define the list,<dl></dl>, define the list usually and<dt></dt>and<dd></dd>Tag together

form

  1. Table label<table></table>
  2. A row of tables<tr></tr>
  3. The head of a table<th></th>
  4. The cell<td></td>
  5. Table merge, the same row, merge several columnscolspan="2"Merge several rows in the same columnrowspan="3"

The form tag

  1. The form tag<form>

Is a form that sends data from the viewer to the server, so that the server can process the data from the form.

<form method=" transfer mode "action=" server file ">

Action, where the data entered by the viewer is sent

Method, the method by which data is transmitted

  1. Enter the label<input/>

Name: The name of the text box used to submit the form and for the background to receive data.

Value: Sets the default value for the text input box.

Type: The input function is different by defining different type types.

Text Single-line text input box Password Input box (the password is displayed as ***) Radio checkbox (checked property is used to display the checked state) Checkbox (checked property is used to display the checked state) file Upload file button Normal button: reset button (clicking the button triggers the form's reset event) Submit button (clicking the button triggers the form's reset event) Email is used to enter the email url is used to enter the URL Number is used to enter the number range is displayed as a slider, which is used to enter the value within a certain range date is used to select the date and time (also includes: Month, Week, Time, dateTime, datetime-local) color Select the colorCopy the code

Button button, drop-down box

<option value=" submit value "> Options </option> are each of the options in the drop-down boxCopy the code
  1. Text fields:<textarea></textarea>The text field is used when the user wants to enter a large amount of text.cols, the number of columns in the multi-row input field,rows, the number of lines in the multi-line input field.

Other semantic tags

  1. box<div></div>
  2. Page header<header></header>.html5Added semantic tags to define the head of the page, mainly used for layout, split the structure of the page
  3. At the bottom of the information<footer></footer>.html5Added semantic tags to define the bottom of the page, mainly used for layout, split the structure of the page
  4. navigation<nav></nav>.html5Added semantic tags that define a navigation, mainly for layout, to split the structure of the page
  5. The article<article></article>.html5Added semantic tags that define an article and are mainly used for layout, splitting the structure of the page
  6. The sidebar<aside></aside>, semantic tags, define information outside of the topic content, mainly used for layout, split the structure of the page.
  7. Time stamp<time></time>, semantic tags, define a time

The web structure

  1. <! DOCTYPE html>Define a document type that tells the browser which standard to interpretHTML
  2. <html></html>Can tell the browser itself is aHTMLThe document
  3. <body></body>The content between the tags is the main content of the web page
  4. <head></head>The tag is used to define the header of the document and is the container for all header elements
  5. <title></title>The element defines the title of the document
  6. <link>The label willcssStyle file links toHTMLIn the file
  7. <meta>Define the metadata of the document

Module partition

  1. Common enterprise website, more by the head area, display picture area, subject area, the bottom of the information area
  2. The principles of splitting web pages are as follows: – Top to bottom – inside to out

CSS Code Syntax

  1. CSSCascading Style sheets(Cascading Style Sheets)It is mainly used for definitionHTMLThe style in which content is displayed in the browser, such as text size, color, bold font, etc.
  2. cssCode is usually stored in<style></style>tag
  3. cssStyles consist of selectors and declarations, which consist of properties and values
  4. selector{attribute: value}
  5. Selectors: Also known as selectors, indicate the elements in a web page to which style rules should be applied

CSS Placement

  1. Inline styles are not recommended
  2. Inline style sheets
  3. External style sheets

CSS inheritance

  1. CSSInheritance is a rule that allows styles to apply not only to a particular HTML tag element, but also to its descendants.
  2. Non-inheritable styles:Display, margin, border, padding, background, height, min-height, max-height, width, min-width, max-width, overflow, position, left, r Top, bottom, z-index, float, clear
  3. Inheritable styles:Letter-spacing, word-spacing, white-space, line-height, color, font, font-family, font-size, font-style, font-weight , text-decoration, text-transform, direction, visibility, cursor

The type of selector

  1. Label selector: Modify by label namecssstyle
  2. Wildcard selector: Selects all the elements in the page
  3. Attribute selector
  4. Descendant selector: Selects all elements below a parent element
  5. Level 1 child element selector: selects the immediate children of a parent element, and the descendant selector selects all the children of the parent element. Level 1 child element selector selects only the first level child element, and does not search for the element down
  6. idSelector: PassedidFind the unique tag on the page
  7. classSelector: by specificclassClass to find the corresponding tag on the page to.classThe name of the
  8. Pseudo-class selector::hoverMouse over an element;:beforeInsert content before an element;:afterInsert content after an element
  9. Group selectors: You can set the same style for multiple different selectors

The priority of the selector

  1. When there are different selectors that style the same object, and two selectors that have the same property are assigned different values.
  2. Which selector style to apply by calculating which selector has the highest weight
  3. Weight calculation method:
Tag selector: 1 Class selector: 10 ID selector: 100 Inline Style: 1000! Important highest level, which increases the style weight and has the highest levelCopy the code

Background style

  1. The background colorbackground-color
  2. The background imagebackground-image
background-image:url(bg01.jpg);
Copy the code
  1. Background Image locationbackground-position
background-position:10px 100px; // represents the x and y axesCopy the code
  1. Background image repetitionbackground-repeat
Background - repeat: no - repeat / / no - not to repeat, repeat set images commonly used / / round automatically zoom until adapt and fill the whole container / / space at the same distance between flat out and fill the whole containerCopy the code
  1. Background image positioningbackground-attachment
Background - attachment: whether fixed or fixed / / background image as the rest of the page scroll / / background - attachment value can be a scroll roll (follow), fixed (fixed)Copy the code
  1. backgroundabbreviations
background:#ff0000 url(bg01.jpg) no-repeat fixed center
Copy the code

Font style

  1. Font familyfont-family
Font-family :" Microsoft Yahei "," black ";Copy the code
  1. The font sizefont-size
font-size:12px;
Copy the code

The default font size for web pages is 16px

  1. The font sizefont-weight
font-weight:400; Normal (default) bold (bold) bolder (equivalent to <strong> and <b> tags) lighter (normal) 100 ~ 900 hundred (400=normal, 700=bold)Copy the code
  1. The font colorcolor
Color :red; Color: #FFFF00; Color: RGB(255,255,0) RGBA (red, green, blue) A is the value of transparency between 0 and 1. Color: rgba (255255,0,0.5)Copy the code
  1. The italic fontfont-style
Font-style :italic normal Text-oblique text-oblique displayCopy the code

Text attributes

  1. Line heightline-height
line-height:50px;
Copy the code

You can prop up the height of the parent element

  1. Horizontal text alignmenttext-align
Left Align the text to the left. Center Center the text. Right Align the text to the rightCopy the code
  1. Vertical alignment of text line heightvertical-align
Baseline sub aligns the text subscript vertically, which has the same effect as the <sub> label. Same as the <sup> tag. The top of the top object is aligned with the top of its container. The top of the top object is aligned with the top of the text on the line The bottom of the object is aligned with the bottom of the text on the lineCopy the code
  1. Text indentationtext-indent
text-indent:2em;
Copy the code

Usually used to indent the first line at the beginning of a paragraph

  1. The space between lettersletter-spacing
  2. Spacing between wordsword-spacing
  3. Case of texttext-transform
Capitalize each word in the text begins with a capital letter. Uppercase defines only uppercase letters. Lowercase defines only lowercase letters.Copy the code
  1. Embellishment of texttext-decoration
None by default. Underline underline. Overline Indicates the crossed line. The line - through the midline.Copy the code
  1. Word wrapword-wrap
word-wrap: break-word;
Copy the code

Basic styles

  1. The width of thewidth
width:200px; Defines the width of the elementCopy the code
  1. highlyheight
Height :300px By default, the element has no heightCopy the code
  1. The mouse stylecursor

Define the style cursor:pointer for the mouse

Default Default pointer Small hand shape move move shapeCopy the code
  1. transparencyopacity
Opacity: 0.3Copy the code
A number between 0 and 1, where 0 represents transparency and 1 represents a completely opaque and transparent element that is invisible but still dominates the document flowCopy the code
  1. visibilityvisibility
visibility:hidden; When used in table elements, this value removes a row or column without affecting the layout of the table.Copy the code
  1. Overflow hiddenoverflow

Sets how to display an object’s content when it exceeds its specified height and width

Visible by default, the content will not be clipped and will appear outside the element box. Hidden content is pruned, and the rest of the content is not visible. The Scroll content will be trimmed, but the browser will display the scroll bar to view the rest of the content. Auto If the content is trimmed, the browser displays a scroll bar to view the rest of the content.Copy the code
  1. Border coloroutline

The input text input box comes with an ugly border, which can be changed by outline

outline:1px solid #ccc; Outline: None Clears the borderCopy the code

Style reset

In the early web pages, there was no CSS style. In order to make the interface beautiful, many elements had built-in margin, padding and other styles. However, these styles had different values in different browsers, so the CSS style needed to be reset to ensure consistent display in different browsers.

Clear the margin and padding of the elements and remove the built-in list character and remove the built-in underscoreCopy the code

Box model style

  1. Block, inline, and inline block elements.

Block-level elements:

  • Each block-level element starts on a new line, and the elements that follow it start on another line.
  • The height, width, row height, and top and bottom margins of the element can be set.
  • The width of an element, when not set, is 100% of its own parent unless a width is set.

Inline elements:

  • And everything else on one row
  • The height, width, row height, and top and bottom margins of the element cannot be set
  • The width of an element is the width of the text or image it contains and cannot be changed.

Inline block elements:

  • And everything else on one row
  • The height, width, row height, and top and bottom margins of the element can be set.
  1. Element classification conversiondisplay

Block: Converts an element to a block-level element

Inline: Converts elements to row-level elements

Inline-block: Converts an element to an inline block element

None: Hides the element

  1. strokeborder
border:2px solid #f00;
Copy the code

Line style:

Dashed (dashed line) | dotted line (point) | solid (solid line).Copy the code

CSS styles allow you to style borders in only one direction:

Border-bottom :1px solid red; Border-top :1px solid red; Border-right :1px solid red; Border-left :1px solid red;Copy the code
  1. spacingmargin
div{margin:20px 10px 15px 30px; }Copy the code
  1. Fill inpadding
padding:10px
Copy the code

Float float

  1. Floating principle
  • Float causes an element to float above the normal flow of the document.

  • The float element still appears in its normal flow position, and then floats as far left or right as possible, depending on the float direction set, until the outer edge of the float element encounters a containing box or another float element, allowing text and inline elements to surround it.

  • Floating produces a block-level box (equivalent to setting display:block) regardless of what the element itself is.

  1. Clear the impact of the float

Clear Clear float:

None: do not clear (default value). Left: Floating objects are not allowed on the left. Right: Floating objects are not allowed on the right. Both: Floating objects are not allowed on both sidesCopy the code
  1. Using pseudo class to achieve clear floating
.clearFix {
  	content="";
  	display:block;
  	width:0;
  	height:0;
  	clear:both;
}
Copy the code

Locate the position

  1. The positioning function can make the layout more free.
  2. Layer model – Absolute positioning (relative to parent)

Absolute positioning makes the position of an element independent of the document flow and therefore does not take up space. This is different from relative positioning, which is actually considered part of the normal flow positioning model because the element’s position is relative to its position in the normal flow.

#box_relative {
  position: absolute;
  left: 30px;
  top: 20px;
}
Copy the code

As shown in the figure below:

To set absolute positioning for an element in the layer model, you need to set Position: Absolute. This drags the element out of the document flow and then uses the left, right, top, or bottom attributes to absolutely position the element relative to its nearest parent containing block that has a positioning attribute. If no such containing block exists, then relative to the body element, that is, relative to the browser window.

  1. Layer model — Relative positioning (relative to original location)

Relative positioning is a very easy concept to grasp. If an element is positioned relative to each other, it will appear at its position. This element can then be moved “relative to” its starting point by setting its vertical or horizontal position.

#box_relative {
  position: relative;
  left: 30px;
  top: 20px;
}
Copy the code

As shown in the figure below:

If you want to set relative positioning for an element in the layer model, you need to set position:relative, which uses the left, right, top, and bottom attributes to determine the offset position of the element in the normal document flow. Relative positioning is accomplished by first generating an element in static(float) mode (and floating like a layer) and then moving relative to its original position. The direction and amplitude of the move are determined by the left, right, top, and bottom attributes, leaving the position before the offset unchanged.

  1. Layer model – Fixed positioning (relative to web window)
position:fixed
Copy the code

Similar to the Absolute positioning type, but its relative moving coordinate is the view (the web page window inside the screen) itself. As the view itself is fixed, it will not change along with the scroll bar of the browser window scroll, unless you are moving across the screen the screen position of the browser window, or change the display size of the browser window, so the fixed position of element is located in a certain position of the view within the browser window, will not be affected by the document flow, This has the same function as the background-attachment: Fixed property.

Default browser style

  1. Page margins

The default value for IE is 10px, set by the body margin property

Both attribute values must be cleared to clear margins

body { margin:0; padding:0; }Copy the code
  1. Paragraph spacing

The default value of IE is 19px, set by the margin-top property of p

P defaults to block display, to clear the segment spacing, generally can be set

p { margin-top:0; margin-bottom:0; }Copy the code

html5

The advantage of it

  1. Solve cross-browser, cross-platform issues
  2. To enhance thewebApplication of

HTML5 deprecated Elements

frame frameset noframes
acronym applet dir
basefont big center font strike tt
Copy the code

New elements of HTML5

<header> Header used to define a document or section <footer> Footer used to define a document or section <article> Article used to define an article within a document <section> Area (or section) used to define a document <aside> <figure> is used to define a single reference, often in conjunction with caption < figCaption >, usually used with images, codes, tables, etc in the main article. The < figCaption > is used to indicate that there is a reference associated with it and to describe other data in its parent <figure> element. <hgroup> is used to combine multiple <h1>~<h6> elements <nav> is used to define the navigation link section on the page <mark> is used to define the highlighted text <time> Is used to show whether the annotated content is date or time (in 24 hours) <meter> The counter <progress> used to represent a known maximum and minimum is used to represent a progress bar <audio> defines sound, such as music or other audio streams <video> defines video, such as movie clips or other video streamsCopy the code

HTML5 form-related elements and attributes

Input added the type color to create a color selector that allows users to use it. Datetime (UTC) datetime (UTC) datetime (UTC) datetime (UTC) datetime (LOCAL) datetime (UTC) datetime (UTC) datetime (LOCAL) datetime (UTC) datetime (UTC) datetime (UTC) datetime (UTC) Date pickers can be used at the same time. The resulting values include the year, month, and day, but not the time. Week generates a selector for a selected number of weeks. Email generates an E-mail field. Number generates a numeric field. Make the user can only enter the specified range, specify the step value search to generate a specialized text box for entering search keywords tel to generate a text box for entering only phone numbers URL to generate a URL input boxCopy the code
HTML5 Input has a new property named placeholder, which is used primarily in text boxes. Autocomplete provides a short prompt that describes the expected value of the input field. Select AutoFocus. When you add this property to a form control, when the browser opens the page, the form control automatically gets the Focus List, which specifies a list of available options for the text box. When the user enters information into the text box, based on the characters entered, The drop-down list prompts are automatically displayed for users to select pattern to validate the form input. Generally, HTML5 type attributes, such as email, TEL, number, URL, etc., already have simple data format validation functions. Validation will be more efficient. Novalidate does not validate the form when it is submitted. Add a new attribute formencType for <input>, <textarea>, and so on. Formenctype specifies how the form data should be encoded before being sent to the server. Maxlength wrap <textarea> add <br />maxlength: specifies the maximum number of characters in the textarea. <br />wrap: soft/ hardCopy the code

css3

CSS3 Added a selector

  1. Sibling selector

Elements 1 through 2 after the first element, all elements 2 are selected and have the same parent as the first element (the two elements do not have to be adjacent).

  1. Property selector
  • E[attribute^=value]Used to select an element with an attribute value beginning with the specified value
  • E[attribute$=value]Used to select the element whose attribute value ends with the specified value
  • E[attribute*=value]Used to select the element in the attribute value that contains the specified value, with no limit on location or on the entire word
  1. Pseudo-class selector
  • :rootSelect the root element of the document, in HTML, always<html>The element
  • :last-childAdds a style to an element that is the last child of its parent element
  • :nth-child(n)Adds a style to an element that is the NTH child of its parent element
  • :nth-last-child(n)Adds a style to an element that is the NTH reciprocal child of its parent element
  • :only-childAdds a style to an element that is the only child of its parent element
  • :first-of-typeAdds a style to an element that is the first element of its type and sibling
  • :last-of-typeAdds a style to an element that is the last element of its type and sibling
  • :nth-of-type(n)Adds a style to an element that is the NTH element of its type and sibling
  • :nth-last-of-type(n)Adds a style to an element that is the NTH penultimate element of the same type as its sibling
  • :only-of-typeAdds a style to an element that is unique among elements of the same type and sibling
  • :emptyAdds styles to elements that have no child elements, including text content
  1. Pseudo-element selector
  • :enabledAdds a style to an element that is currently available, usually to define a style for a form or a hyperlink
  • :disabledAdds a style to an element that is currently unavailable, usually to define a style for a form or a hyperlink
  • :checkedAdds a style to the element that is currently selected
  • :not(selector)To notselectorAdds styles to the elements of the
  • :targetAdds a style to the anchor point target element being accessed
  • ::selectionAdds a style to the element where the user is currently selecting content

CSS3 Added attributes

  1. Add background attribute
  • background-clipSet the background coverageborder-box/paddingbox/content-box
  • background-originSets the starting point of the background overlayborder-box/paddingbox/content-box
  • background-sizeSet the background sizeCover /contain/ contain/ contain
  1. New font text-related properties
  • text-overflowSets what to do when text overflows the element boxclip/ellipsis
  • word-wrapSpecifies how words are newlinenormal/break-word
  • word-breakSpecifies how to wrap linesnormal/break-all/keep-all
  1. Added box model properties
  • box-shadowshadowh-shadow v-shadow <br />blur spread color inset
  • resizeAdjust the sizenone/both/horizontal
  • outline-offsetThe offset of the contourlength/inherit

Added deformation animation properties

  1. transform
  • translate(x,y)
  • rotate(angle)
  • scale(x,y)
  • skew(angleX ,angleY)
  1. transform-origin

Represents the center point of the element rotation. The default value is 50% 50%.

  • The first value represents the horizontal position of the center point of the element rotation. It can also be assigned left, right, center, length, and percentage

  • The second value represents the vertical position of the center point of the element rotation. It can also be assigned to top, bottom, center, length, and percentage.

3D deformation properties

  1. transform 3Dfunction

Transform adds three transform functions:

  • rotateX: indicates that the element is alongxShaft rotation.
  • rotateY: indicates that the element is alongyShaft rotation.
  • rotateZ: indicates that the element is alongzShaft rotation.
  1. Transform-style is used to set the effect of nested child elements in 3D space.

  2. Perspective is set to the perspective effect, the perspective effect is near large, far small.

  3. Perspective-origin sets the X-axis and Y-axis on which the 3D element is based, and changes the bottom position of the 3D element. This property has the same value as transform-Origin, which defaults to 50% 50%.

  4. Backface-visibility is used to set whether the back of the element is visible when it faces the screen. It is usually used to set that the user does not want to see the back of the rotated element.

Its property values are visible (the default) and hidden (the back is not visible).

Transition properties of CSS3

  • transition-delaySet the delay time for the transition
  • transition-durationSet the transition time for the transition
  • transition-timing-functionSet the time curve for the transition
  • transition-propertyWhich setting.CSSUse the transition
  • transitionOne declaration sets all transitional properties

CSS3 animation properties

  1. animation
  • @keyframesDefine the animation selector
  • animation-nameuse@keyframesDefined animation
  • animation-delaySets the duration of the animation
  • animation-timing-functionSet the time curve of the animation
  • animation-iteration-countSet the number of times the animation is played
  • animation-directionSet the animation to play backwards
  • animation-play-stateSet the animation playing state
  • transitionOne declaration sets all animation properties

CSS3 adds new column attributes

  • column-countSets the number of columns the element should be separated from
  • column-widthSets the width of the column
  • columnsA declaration sets the column width and number of columnscolumn
  • column-gapSets the interval between columns
  • column-spanSets the number of columns that the element should span
  • column-rule-styleSets the style for spacing between columns
  • column-rule-colorSets the color of the interval between columns
  • column-rule-widthSets the width of the interval between columns
  • column-ruleOne declaration sets all properties between columns

CSS3 Added units

Px, EM, REM, VH, VW and % mobile terminal length units

Use CSS units px, EM, REM, VH, VW, etc.

  • px: Absolute unit. The page is displayed in exact pixels
  • em: Relative unit. The reference point is the font size of the parent node, if definedfont-sizeBy itself (the default browser font is16px), the entire page1emIt’s not a fixed value.

Em varies according to the size of the parent element, but if multiple elements are nested, calculating its size is error-prone, and thus rem is derived.

  • rem: Relative unit, which can be understood as"Root em", relative to the root nodehtmlTo calculate the font size,CSS3Add new properties.
  • %:%Percentage, a unit of relative length, the percentage value relative to the parent element
  • Vw, VH, Vmin, vmaxMainly used for page viewport size layout

Vw: Viewpoint width, window width, 1vw is equal to 1% of the window width.

The viewpoint is 1% of the window height.

  • Vmin: vwandvhThe middle and smaller one.
  • Vmax: vwandvhThe larger of the medium.

Elastic box model

Basic grammatical concepts of elastic box model

Any container can specify an elastic layout

JavaScript

JavaScript based

  1. External introductionjsFile: Approved<script src="main.js"></script>
  2. keywords

  1. Variable names are case sensitive
  2. Naming conventions

JavaScript data types

  1. string(String)
  2. digital(Number)
  3. Boolean value(Boolean)
  4. undefined(Undefined)
//undefined (alert(typeof dada)); Var dada; //undefined; alert(dada); //undefinedCopy the code

Undefined, which means undefined or declares only variables with no given value

  1. object(Object)

Js has the following built-in objects:

  • ObjectIs the superclass (base class) of all JS objects. All objects in JS are inherited from Object
  • ArrayAn array object defines array properties and methods
  • NumberDigital objects
  • BooleanBoolean object Boolean value correlation
  • ErrorError object handler error
  • FunctionFunction objects define function properties and methods
  • MathMathematical objects
  • DateThe date object
  • RegExpObject Regular expression objects define text matching and filtering rules
  • StringString objects define string properties and methods

Arithmetic operations

var y = 3;
Copy the code

Casts.

  1. String to numberparseInt() parseFloat() isNaN()
  2. Number to stringtoString()

The assignment operation

  1. Compound assignment operator+= -= *= /= %=

Relationship between operation

  1. Relational operations:> < <= >=! === === == and ===! = and! = =

"=" "==" "==="What’s the difference?

  1. =Is an assignment symbol
  2. = =Ignore the datatype to determine equality
  3. = = =The value and data type must be equal to each other

Logical operations

  • Logic and&&
  • Logic or||
  • Logic is not!
  • Complex logical expression

The ternary operation

Conditional operators? : ternary operator: (comparison expression)? Result 1: Result 2Copy the code

Branch loop

The three main structures of program operation are sequence structure, selection structure and loop structure

  • Single branch selection:ifstatements
  • Dual branch selection:if-elsestatements
  • Multiple branch statements:if-else if-elsestatements

switch

Syntax format

Case 1: // execute block 1 break; // Interrupt execution, jump out... Default: // default, execute if nothing else; // Execute block break; } // Emphasize that a break is very important; if not, the program will continue;Copy the code

while

Syntax format:

While loops are best used when you don’t know how many times they will be executed

While (conditional expression){// Section of code to repeat - body of loop}Copy the code

do-while

Syntax format:

Do {// loop body}while(loop condition);Copy the code
  • do-whileIs to execute the body of the loop first and then check the loop condition.
  • do-whileEnsures that the body of the loop executes at least once.
  • Other loops have no guarantee that the loop will execute at least once.

for

For (1 loop variable initialization; 2. Cyclic condition judgment; 4 loop variable modification){3 loop body}Copy the code

Break and continue

  1. breakExit the loop
  2. continueSkip this loop and continue the next one

An array of

  1. To define an array
var arr = new Array();
var arr = [];
Copy the code
  1. Definition in a literal way
var arr = ["1","2"];
Copy the code
  1. Assign values to arrays
arr[0] = "1";
arr[1] = "2";
alert(arr[0]+","+arr[1]);
Copy the code
  1. Array index
arr[0]+","+arr[1]
Copy the code
  1. The length of the array
// Syntax arr.length // Index of the last element arr.length-1Copy the code

Array methods

  1. indexOf

An array can be searched for the location of a specified element by using indexOf(), returning -1 if not found

  1. concat

The concat() method concatenates the current array with another array and returns a new array

var newArr = arr1.concat(arr2,"dada");
Copy the code
  1. Push and pop

Push () adds elements to the end of the array, and pop() removes the last element from the array

arr.push("a","b"); console.log(arr); arr.pop(); console.log(arr); // If the array is empty, pop will return undefinedCopy the code
  1. Unshift and shift

Unshift () adds elements to the front of the array, and shift() removes the first element

arr.unshift("a","b");
arr.shift();
Copy the code
  1. slice

Slice () cuts off some elements of an array and returns a new array

The console. The log (arr. Slice (0, 3)); Log (arr.slice(3)); // Start with index 0 and end with index 3, but not 3 console.log(arr.slice(3)); // Start with index 3 and end with index 3Copy the code

If you don’t pass any arguments to slice(), all elements are truncated from beginning to end. Taking advantage of this, you can easily make a new copy of the array

  1. sort

Sort () sorts the current array

var arr = ["b","c","a"]; arr.sort(); arr; //["a","b","c"]Copy the code
  1. reverse

Reverse () drops the elements of the entire array

  1. join

The join() method concatenates each element of the array with the specified string

var arr = ["a","b","c"];
arr.join("-"); //"a-b-c"
Copy the code
  1. splice

You can delete elements starting at the specified index and then add elements from that location

2 d array

Var arr = [[1, 2, 3], [" a ", "b", "c"], "dadaqianduan"]. var x = arr[1][1]; //bCopy the code

string

  1. String attributelength– The length property of the string
  2. slice()
Slice (start[,end]), start-- start index end-- end indexCopy the code
  1. substr()
Substr (start[,length]), start: start. The value is a length characterCopy the code
  1. split()

Split ([separator[,limit]]), splits the string conditionally, returning an array

  1. indexOf()

The first occurrence in the parent string, starting at 0! Negative 1 is not returned

  1. lastIndexOf()

Reverse lookup

  1. charAt(index)

CharAt (index) Specifies the index character

  1. toLowerCase()

Turn to lowercase

  1. toUpperCase()

Turn the capital

Regular expressions

Creating a regular expression

var reg = new RegExp("a","i"); // Matches the letter a, with the second argument, I, indicating that the match is case insensitiveCopy the code

metacharacters

Pattern modifier

The regular way

  1. testmethods

Retrieves the specified value in the string.

  1. execmethods

This method is used to retrieve the match of a regular expression in a string. This function returns an array containing the result of the match. If no match is found, null is returned.

Support for regular String methods

Js object

Define the object

// Use the new operator var obj = new Object(); Var obj={name:"dadaqianduan", age:12, sex:" male "}Copy the code

Object

Obj ["name"] obj["name"]Copy the code

JSON

Json (JavaScript Object Notation) is a lightweight data exchange format.

Var man = {" name ":" dadaqianduan ", "age" : 12, "sex", "male"};Copy the code

Built-in objects

  • ObjectIs the superclass (base class) of all JS objects. All objects in JS are inherited from Object
  • ArrayThe array object
  • NumberDigital objects
  • BooleanThe Boolean object
  • ErrorError object
  • FunctionThe function object
  • MathMathematical objects
  • DateThe date object
  • RegExpObject Indicates the regular expression object
  • StringString object

Math methods

  • abs()Absolute value (minus plus and minus)
  • random()The random number,0-1Between random numbers,1There will be no
  • round()rounded
  • floor(x)Round down (round down)
  • ceil(x)Round up (round up)
  • max(x,y) X and yThe maximum of
  • min(x,y) X and yThe minimum value in
  • cos(x) xThe cosine
  • sin(x) xThe sine
  • sqrt(x)returnxThe square root of
  • Pow (3, 4)return3the4To the power

The Date methods

  • getFullYear()Year of Return (4th)
  • getMouth()Return month (0–11)
  • getDate()Return date
  • getDay()Return Week (0-6)
  • getHours()Returns the hour
  • getMinutes()Returns the minutes
  • getSeconds()Return to the second
  • getTime()Returns the number of milliseconds between midnight, January 1, 1970, and the specified date (string)
  • setFullYear()Set the date
  • setMouth()Set the month
  • setDate()Set the day
  • setHours()Set hours
  • setMinutes()Set the minutes
  • setSeconds()Set up the second
  • setTime()Set the time object in milliseconds
Function runYear(year){if(year%4==0 && year%100! =0 || year%400==0){ return true; }};Copy the code

Object orientation is a programming idea

  1. A class is an abstract concept
  2. Object: something concrete
  3. A class is an abstraction of an object, which is a concrete instance of a class
  4. Classes do not take up memory; objects take up space
  5. Object to declare the object
  6. Traversal objects –for incycle

Define the object

  1. Literal creation
  2. The factory pattern
Function Cat(n,c){return {name:n, color:c, say:function(){alert("dadaqianduan")}}Copy the code
  1. The constructor

Javascript provides a Constructor pattern.

A “constructor” is just a normal function, but it uses this internally.

Using the new operator to the constructor, the instance is generated, and the this variable is bound to the instance object.

The constructor starts with a capital letter

The instantiated object to which this is referred in the constructor

function Cat(n,c){
  this.name=n;
  this.color=c;
}
Copy the code

Generate instance objects

Var cat1 = new Cat("dadaqianduan"," yellow ") var cat1 = new Cat("dadaqianduan"," yellow ")Copy the code

Examples: automatically contain a constructor property that points to their constructor

alert(cat1.constructor == Cat); //true
Copy the code
  1. JavascriptIt also provides oneinstanceofThe operator

Verify the relationship between the prototype object and the instance object.

var txt = 'dadaqianduan';
alert(txt instanceof String); //false

var age = 123123;
alert(age instanceof Number); //false

var res = /\d/;
alert(res instanceof RegExp); //true

var arr = [];
alert(arr instanceof Array); //true
Copy the code

Prototypes and prototype chains

Each constructor has a Prototype property that points to another object. All properties and methods of this object are inherited by the instance of the constructor.

All functions are instances of Function.

Each constructor has a property called prototype, which is also an object; This object has a constructor property that points to the constructor.

There is a _proto_ property on the instance object, which also points to the prototype object. This property is not a standard property and cannot be used in programming. This property is used within the browser.

constructor

  1. constructorIs a property of the instance created by the constructor. This property points to the constructor that created the current object.
son.constructor == parent; // true
Copy the code

Each stereotype has a constructor property that points to the associated constructor.

function Person() {
}

console.log(Person===Person.prototype.constructor)  //true
Copy the code

Diagram:

Distinguish between normal objects and function objects

function f1(){}; var f2 = function(){}; var f3 = new function(){}; var o1 = {}; var o2 = new Object(); var o3 = new f1(); console.log(typeof Object); //function console.log(typeof Function); //function console.log(typeof f1) //function console.log(typeof f2) // function console.log(typeof f3) //function console.log(typeof o1) //object console.log(typeof o2) //object console.log(typeof o3)// objectCopy the code
  1. inJavaScriptA stereotype is an object. The function of a stereotype is to implement object inheritance.
  2. inJavaScriptThere is a property,prototype, which corresponds to the stereotype of the current object.
  3. All of theJavaScriptObject, there is one_proto_Properties,_proto_Property points to the prototype of the constructor for the instance object.
var p = new Person(); // instance object console.log(p._proto_ === person.prototype); // trueCopy the code

P is the instance object, and Person is the constructor for P. The _proto_ property of p points to the prototype of the constructor Person.

How js inherits through prototypes:

var parent = function(name) {
 this.name = name;
}

parent.prototype.getName = function() {
 return this.name;
}

var son = new parent("dadaqianduan");

console.log(son.getName()); // dadaqianduan
Copy the code

Son inherits the function attribute getName from parent’s stereotype

Prototype chain

All objects and prototypes have their own prototype, with the exception of Object’s prototype, whose prototype is null.

In a hierarchical relationship, a chain of prototypes is formed by connecting multiple prototypes.

When looking for a property of an object, if the current object cannot find the property, it will search up the stereotype chain until it is found. If it reaches the top of the stereotype chain and is not found, undefined is returned

The prototype

  1. All reference types have one__proto__attribute
  2. All functions have oneprototypeattribute
  3. All reference types__proto__Property that points to its constructorprototype

The relationship between constructors and instance prototypes:

The prototype of Person (constructor) points to person.prototype

  1. __proto__

Every object, except null, has a property called __proto__, which points to the object’s prototype.

function Person() {
}
var person = new Person();
console.log(person.__proto__ === Person.prototype); // true
Copy the code

Diagram:

Diagram:

Diagram:

Carding:

Write a constructor named Person, which differs from normal functions by requiring the first letter to be uppercase:

function Person(){}
Copy the code

The prototype prototype

A prototype is an object that has a property defined on its prototype. By “inheritance”, an implementation instance also has this property.

Inheritance is implemented inside the new operator.

The constructor has a prototype property inside it that allows you to access the prototype.

Person is the constructor, and person. prototype is the prototype.

  1. The instance

There are constructors to create inheritable properties on stereotypes, and instances are created with the new operator:

Function Person(){} Person = new Person() da = Person instanceof Person // check if Person is an instanceof Person Function Person() {} person.prototype. name = 'dadaqianduan.cn' Person = new Person() da = person.name 'dadaqianduan.cn'Copy the code
  1. proto

The instance accesses the stereotype through _proto_.

function Person() {}
Person.prototype.name = 'dadaqianduan.cn'

person = new Person()

da = person.__proto__ === Person.prototype

da // true
Copy the code
  1. constructorThe constructor

Stereotypes can also be accessed via constructor

function Person() {} Person.prototype.name = 'dadaqianduan.cn' person = new Person da = Person.prototype.constructor ===  Person da // trueCopy the code

summary

  1. All reference types (functions, arrays, objects) are owned__proto__Properties.
  2. All functions haveprototypeProperties.
  3. Each instance object (Object) has a private property, for__proto__The prototype object that points to its constructor (prototype). The prototype object also has a prototype object of its own__proto__, layer up until an object whose prototype object isnull.nullThere is no prototype, and as the last link in the prototype chain.

Common JavaScript design patterns

Baidu Encyclopedia:

A Design pattern is a set of repeatedly used, widely known, catalogued and catalogued code Design experiences.

Design patterns are used to make code reusable, easier to understand, and reliable. There is no doubt that design patterns are all-win for themselves, others and the system; Design patterns make coding truly engineering; Design patterns are as fundamental to software engineering as they are to the structure of a building.

A singleton

A monomer is an object that divides a namespace and groups a set of related properties and methods together. It can only be instantiated once, if at all.

Features:

(1) The namespace can be divided to clear the danger of global variables.

(2) Use branching technology to encapsulate differences between browsers.

(3) The code can be organized more integrated, easy to read and maintain.

The factory pattern

Definition of factory pattern:

Provides an interface for creating objects, which means producing corresponding products (objects) according to the instructions (parameters) of the leader (caller).

  1. Creating an object is often a complex process, so it is not appropriate in a complex object.
  2. Creating objects can lead to a lot of repetitive code and may not provide a sufficient level of abstraction.

A factory transfers the creation of member objects to an external object, with the benefit of eliminating the coupling (that is, the interaction) between the objects.

Classification:

Simple factory pattern: Use a class, usually a single, to generate an instance.

Complex factory pattern definition: Pushes the instantiation of its member objects to subclasses, and subclasses can override the interface methods of the parent class to specify their own object types at creation time.

The parent class handles only the general problems in the creation process, which are inherited by the subclasses, which are independent of each other, and the concrete business logic is written in the subclasses.

Application scenario:

The factory model is particularly useful in the following scenarios:

(1) Object construction is very complex;

(2) Create different instances depending on the specific environment;

(3) Handle a large number of small objects with the same properties.

The singleton pattern

The singleton pattern defines the creation of an object that has a single instance and provides a global point of access to it. In other words, a singleton is a guarantee that there is only one instance of a class. The way to do this is to determine whether the instance exists, and return it if it does exist. If it does not exist, create it and return it.

Using closures to implement singletons:

var single = (function(){ var unique; Function getInstance(){if(unique === undefined){unique = new Construct(); } return unique; } function Construct(){ // ... } return {getInstance: getInstance}})();Copy the code

Unique is a reference to the object that is returned, and getInstance is a static method that gets the instance. Construct is the constructor that creates the instance.

Singletons can be retrieved via single.getInstance(), and the same singletons are retrieved on each call. This is what the singleton pattern achieves.

Application scenario:

  1. The singleton pattern is a common pattern. There are some objects that we need only one, such as the global cache and the browserwindowObject.
  2. With singletons, you can organize your code more consistently, making it easier to read and maintain.

function

Definition of a function

Function dada(){console.log(" order food "); Console. log(" grab chopsticks "); Console. log(" eat "); }Copy the code

Local variables and global variables

  1. The scope of a variable
  • Variables inside a function: Local variables that can only be used inside a function
  • Variables outside a function: global variables, which are globally visible
  1. A local variable
Function da(){var dadada = "dada"; // Local variable alert(dadada); } da(); / / call alert (dadada); // The function is not visible outside dadadaCopy the code
  1. The global variable
Var da = "I am a global variable "; Function home(){var da = "I'm a local variable "; alert(da); } home(); ----------------------- var a=3; Function (){alert(a); //3 var b=5; alert(b); //5 } da(); console.log(b); // An error is reportedCopy the code

Typical error: variables declared without var are also global (not recommended)

function dada(){ da = "123"; // global} dada(); alert(da);Copy the code

The return value

The meaning of the return

Function getNum(){return 2; } var result = getNum(); // If you want to save the return value, put it in a variable; console.log(result); / / 2Copy the code

Return method

  • returnOnly one data can be returned
  • If it’s not in the functionreturn, the returnundefined

Return can be used to terminate a function

function Fun(){ console.log("helloweb"); return; Console. log(" Will I still execute?" ); } Fun();Copy the code
function fn(){ for(var i=0; i<10; I ++){if(I == 3){return break; } console.log(" Who is the most handsome?" ); // Print three times} return "see if return executes me"; //return is not executed, break is executed}Copy the code

Anonymous functions

Var say = function(){console.log("hello"); var say = function(){console.log("hello"); }; say(); var oBtn = document.getElementById("box"); Obth.onclick = function(){alert(" you clicked me "); }Copy the code

Self-running function

Example:

Function fn(){// here's the code} fn(); / / run the fn function -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the var fn = function () {} / / here is the code fn (); / / run the fn function -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / (fn) () is equivalent to the fn () (function () {/ / here is the code}) ()Copy the code

closure

A function whose closure has access to variables in the scope of another function.

Common ways to create closures are:

  • Create a function inside a function, and take that functionreturnTo go out.
  • You bind an event to an element with a function, and when the event occurs, you can manipulate variables in that function.

features

  1. You can read variables inside other functions
  2. Keep the values of these variables in memory at all times

Example:

Function run(){var a=10; return function(){ a++; console.log(a); }; }; var b=run(); //alert(b); //b is a function b(); // A function that can access variables in another scopeCopy the code
Function addClick(){var TXT ="abcd"; document.getElementById('box').onclick=function(){ alert(txt); }}; addClick();Copy the code
Function play(num,fn){if(num>10){return fn &&fn (num); }; }; var ss=play(20,function(n){ return n+1; }); console.log(ss);Copy the code

BOM

Summary of BOM

BOM Browser Object Model (BOM)

The BOM provides information about objects that interact with the browser window and load the page independently of the content. Its core object is the Window object

There is no standard for a BOM. Each browser defines its own properties, and each has its own way of implementing the BOM

Although W3C has not formulated a standard for BOM, the window object, navigation object and so on have actually become the default standard due to the convergence of functions

The window method

  • alert()Prompt box
  • confirm()A prompt box with a confirm cancel button
  • prompt()A prompt box with a text field that can be entered
  • setInterval()Interval timer that calls functions or evaluates expressions for a specified period (in milliseconds)
  • setTimeout()Timeout timer that calls the function after a specified number of milliseconds
  • clearInterval()Clearance interval timer
  • clearTimeout()Clearing the Timeout Timer
  • requestAnimationFrameFrame the timer

frames [ ]A frameset

The browser window is divided into several frames. Each frame takes multiple urls at the same time and displays different web content.

History Historical records

  • window.history.go(1)Forward (jump)
  • window.history.go(-1)Go back (jump)
  • window.history.forward()forward
  • window.history.back()back

The location positioning

  • window.location.href='http://www.baidu.com/'Page jump
  • window.location.reload()Page reloading

The navigator navigation

Window. The navigator. UserAgent browser type, version, operating system type, the information such as browser engine type

Screen screen

Width returns the current screen width (resolution value) window.screen.height Returns the current screen height (resolution value)

The document document

The document attribute of window represents all HTML elements. This part is the main part of JS operation, so this part must be standardized to carry out unified development. Therefore, the W3C has made this part of the specification – the DOM standard.

DOM

DOM (Document Object Model) defines the objects, behaviors, and properties needed to represent and modify a document, as well as the relationships between these objects.

DOM object methods

  • GetElementById (id)throughidTo obtainDOMObject (object)
  • getElementsByTagName(tag)Obtain by labelDOMObject (” array-like “object)
  • getElementsByName(name)throughnameTo obtainDOMObject (” array-like “object)
  • getElementsByClassName(class)throughclassTo obtainDOMObject (not supported in IE8 below)

Manipulate relationships between DOM

  • createElement(tag)Create the element
  • The removeChild (object)Remove elements
  • The appendChild (object)Insert elements
  • ReplaceChild (Replacement object, replaced object)Replace the element
  • InsertBefore (object, target object)The front of the insert

AppendChild replaceChild insertBefore both have the ability to move objects

Node properties:

ParentNode childNodes firstChild firstChild lastChild lastChild previousSbiling nextSiblingCopy the code

Clone a node:

CloneNode (Boolean) True: copies the node and all its children. False: copies only the node itselfCopy the code

DOM node Properties

  • SetAttribute (" attribute name ", attribute value)Set properties
  • getAttributeRetrieve attributes
  • removeAttributeDelete attributes:
  • hasAttributesDetermines whether the attribute exists (returnedture/false)

The event

var oDiv=document.getElementById('box');
oDiv.onclick=function(){   
	alert('hello world'); 
};
Copy the code
  1. addEventListener( )Adding event listening
  2. removeEventListener( )Deleting an Event Listener

Event classification

  • windowThe event
  1. onloadLoad (when a page or image is completed)
  2. onunloadUser exit page
  3. onresizeThe window or frame is resized
  4. onscrollScrollbar event
  • Mouse events
Onclick mouse click ondblClick mouse double click OnMouseDown mouse button Pressing onMouseup mouse button is released onMouseout mouse is removed from an element onMouseover mouse is moved over an element Onmouseenter mouse into an element onMouseleave mouse away from an element onMousemove mouse movement onContextMenu Right-click menuCopy the code
  • The input event
The onblur element loses focus. The onFocus element gets the focus. Input OnChange is triggered when the content of the input box changes.Copy the code
  • Keyboard events
Onkeydown Press the OnKeyPress key Press and release the OnKeyUp keyCopy the code
  • Form the event
Onsubmit onSubmit onSubmit onSubmit onSubmit onSubmit onSubmit onSubmit onSubmitCopy the code

The event object

Get event data. Different events have different data

Odiv.onclick =function(ev){//ev is the event object}Copy the code

Flow of events

  1. Object’s default behavior
  2. Prevent default behavior:event.preventDefaut()

Flow of events

Event flow direction: capture → event target → bubble

  1. Event capture
  2. Event goals
  3. Event bubbling and preventing event bubbling

Event goals

ev.targrt
ev.target.nodeName
ev.target.tagName
Copy the code

Event delegate(delegate)

Principle: The event is bound to the parent level, and the event is triggered by determining the “target element” of the event by using the event bubble principle

role

  • Do not bind events to child elements separately
  • Bind an event for an unknown element

Event listeners

You can bind multiple events to a single element

Obj. AddEventListener (event, callback, bubble/capture); Btn.addeventlistener ("click",function(ev){//ev event object alert('dadaqianduan'); },false) //false bubble phaseCopy the code

jQuery

A lightweight JS library rich DOM selector simple event operation reencapsulation method, let the operation of DOM properties more simple chain operation rich animation effects Ajax operation support browser compatible plug-in extension development, strong scalability can not backward compatible plug-in compatibility multiple plug-in conflictCopy the code

JQuery selector

  • idThe selector
$('#box')
Copy the code
  • classThe selector
$('.box')
Copy the code
  • Tag selector
$('p')
Copy the code
  • *Represents all labels

Property selector

  • [attribute]Matches the element that contains the given attribute
  • [attribute=value]Matches elements where the given attribute is a specific value
  • [attribute!=value]Matches elements for which the given attribute is not a specific value
  • [attribute^=value]Matching a given attribute is an element that starts with some value
  • [attribute$=value]The assigned attribute is an element that ends in some value
  • [attribute*=value]A given attribute is matched as an element that contains some value

Position selector

:first matches the first element

:last Gets the last element

:not Removes all elements that match a given selector

:even matches all elements with an even index, counting from 0

:odd Matches all elements with an odd index, counting from 0

:eq matches an element with a given index value

:gt Matches all elements greater than the given index

:lt matches all elements less than the given index

Descendant selector

$(" selectors 1, selectors 2... ") )Copy the code

Child selector

$(" selectors 1> selectors 2>... ") )Copy the code

Selector object

$(" selectors ").each(function(index){this}) traverses the selector object $(" selectors ").find() finds the children of the previous element matched by the selector $(" selectors ").not() removes one or more of the previous elements matched by the selector $(" selector ").add() appends the node to the previous selectorCopy the code

Child elements

:first-child matches the first child :last-child matches the last child :first-of-type selects the first sibling of all elements with the same name :last-of-type selects the last sibling of all elements with the same name :nth-child matches the NTH child or even element under its parent :nth-last-child() selects all the NTH child elements of their parent. Counting from the last element to the first :nth-last-of-type() selects all the NTH child elements of their parent elements, counting from the last element to the first :nth-last-of-type() selects all the NTH child elements belonging to the same parent element, If an element is the only child of the parent element, it will be matched :only-of-type selects all elements that have no siblings and have the same element name.Copy the code

The form

:input matches all input, textarea, Select and button elements :text matches all single-line text boxes: Password matches all password boxes :radio matches all radio buttons: Checkbox matches all check boxes: Submit matches all submit buttons: Image matches all image fields :reset Matches all reset buttons :button matches all buttons :file matches all file fields :hidden matches all hidden fieldsCopy the code

Form Object Properties

: Enabled Matches all available elements. Disabled Matches all disabled elements. Checked Matches all selected elementsCopy the code

DOM manipulation

  1. Looking for to get
Text () - sets or returns the text content of the selected element. HTML () - sets or returns the content of the selected element. Val () - sets or returns the value of the form fieldCopy the code
  1. Internal insert
Append () appends all matched elements to another set of specified elements prepend() preends each matched element prependTo() preends all matched elements to another set of specified elementsCopy the code
  1. External insert
After() inserts the contents after each matched element before() inserts the contents before each matched element insertAfter() inserts all matched elements after another, specified set of elements insertBefore() Inserts all matched elements before another, specified set of elementsCopy the code
  1. The parcel
Unwrap () this method removes the parent element from the element. WrapAll () wraps all matched elements in a single element. WrapInner () wraps the children of each matched element (including text nodes) in an HTML structureCopy the code
  1. replace
ReplaceAll () replaces all matched elements in a selector with the specified HTML or DOM elementCopy the code
  1. delete
Empty () removes all child nodes in the set of matched elements. Remove () removes all matched elements from the DOMCopy the code
  1. cloning
Clone () clones the matching DOM elements and selects copies of these clonesCopy the code

JQuery event

Page load

The $(document). Ready (function () {}) / / shorthand $(function () {})Copy the code

event

$("#box").on("click",function(){
    /**/
})

$("#box").off("click,mousemove");
Copy the code

Container to adapt

There are several ways to get the width and height of an element:

$(selectors). The width () | innerWidth () | outerWidth () $(selectors), height () | innerHeight () | outerHeight ()Copy the code
InnerWidth () and innerHeight() are the width and height of the contents of the element plus the width and height of the margins; OuterWidth () and outerHeight() are the width and height of the contents of an element plus the width and height of the margins and borders;Copy the code

The method of obtaining the width and height of the window is as follows:

$(window).width()
$(window).height()
Copy the code

Label Style Operations

The $(selector).css (style property name [, value]) method sets or returns one or more style properties for the selected element. $(selector).addClass adds a category style $(selector).removeclass removes a category style $(selector).toggleclass (class name) interchangeover the class style: remove the class style if it has it, append it if it doesn't;Copy the code

sliding

Show () show the element hide() hide the element slidDown() show the element slideUp() slideUp fold up hide the slideToggle() alternate slide state fadeIn() fadeIn fadeOut() fadeOut fadeTo() Animation to the specified transparency fadeToggle() alternating the fade and fade statesCopy the code

Custom animation

Stop () stops all animations that are running on the specified element Delay () sets a delay to delay subsequent items in the execution queue Finish () Stops the currently running animations, deletes all queued animations, and completes all animations that match the elementCopy the code

AJAX

$.ajax()
Copy the code
$.get() loads the information with a remote HTTP GET request $.post() loads the information with a remote HTTP POST request $.getjson () loads the JSON data with an HTTP GET requestCopy the code

The working principle of

AJAX = asynchronous JavaScript and XML

When you enter the URL address in the browser to request the server, you send the HTTP request to the server through Ajax, and the response result of the service is returned to Ajax first, which is processed by Ajax and then returned to the browser for display on the page.

The XMLHttpRequest object

// Step 1: XHR = new XMLHttpRequest(); Xhr.open ("post","test.php"); // Step 3: xhr.setRequestHeader(" content-type ","application/x-www-form-urlencoded"); // Step 4: xhr.send("a=1&b=2"); Onreadystatechange =function(){if(xhr.status==200 && xhr.readystate ==4){var result= XHR. Alert (result); }}Copy the code

Differences between XML and HTML

The get () and post ()

$.get(url,data,callback,dataType)
$.post(url,data,callback,dataType)
Copy the code

How AJAX works

The basic format of Ajax is as follows:

$. Ajax ({url: 'the requested resource, type:' get | post request way, data: 'send data name = value & name = value', dataType: 'returned value of type' success: function (res) {res receive return values}})Copy the code

HTTP

HTTP (HyperText Transfer Protocol) is a communication protocol that allows hypertext Markup Language (HTML) documents to be transferred from a Web server to a client’s browser.

HTTP Message structure

  • request line

Request line: The first line must be the request line, stating the type of request, the resource to be accessed, and the HTTP version to be used.

  • header

Request header: Specifies additional information to be used by the server.

  • blank line

Blank line: There must be a blank line between the request header and the request body

  • body

Request body: Also called the request body, any other data can be added

The status line:

The value can be: IP: port or domain name User-agent The name of the application that sends the request (browser information) Connection Specifies properties related to the Connection, such as: Connection: keep-alive Accept-charset Encoding format acceptable to the client accept-encoding Data compression format acceptable to the client Accept-language Language referer acceptable to the client Content-type File type of the request Cookie Session information related to the siteCopy the code

Url Request Process

  1. First, the client and server need to establish a connection.
  2. After the connection is established, the client sends a request to the server in the format of uniform resource identifier (URL), protocol version number, client information, and possible contents.
  3. After receiving the request, the server provides the corresponding response information in the format ofA status line, including informationProtocol version number, a success or error code(status CodeStatus code), afterServer Information,Entity informationAnd possible content.
  4. After receiving the information returned by the server, the client disconnects from the server.

If an error occurs at one of these steps, the error message is returned to the client. For the user, the process is done by HTTP itself, by clicking and waiting for the information to appear.

preload

Preloading: All required resources are requested to be loaded locally in advance, and then the resources are directly accessed from the cache when needed

  1. useimageobject
<img src="" style="display:none"/>
Copy the code
  1. useimageobject
var image = new Image();
image.src="";
Copy the code
  1. useXMLHttpRequestobject
xmlhttprequest.onreadystatechange=callback; xmlhttprequest.onprogress=progressCallback; xmlhttprequest.open("GET",http://xx.jpg,true); xmlhttprequest.send(); function callback(){ if(xmlhttprequest.readyState=4 && xmlhttprequest.status==200){ var responseText=xmlhttprequest.responseText; }else{ console.log("Request was unsuccessful" + xmlhttprequest.status); } } function progressCallback(e){ c=e||event; if(e.lengthComputable){ console.log("Received"+e.loaded+"of"+e.total+"bytes"); }}Copy the code

Lazy loading

First screen loading, the technical display technology is to use the image lazy loading, that is, to the visual area to load again.

Performance optimization

JavaScript code optimization

  1. Code is separated from structure
  2. The separation of style and structure
  3. Data is separated from code
  • AMD: Asynchronous Module DefinitionThat is, the asynchronous module loading mechanism.
  • CMD:Common Module Definition, the generic module definition specification
  • export(export)With the import(import)Two modules

Improves file loading speed

  1. mergeJavaScriptCode, use as little as possiblescriptThe label.
  2. Clog-free loadingJavaScript.
  3. Dynamically createscriptTag to load

webpack

Webpack is a Module Bundler, a build tool that has become an integral part of Web development due to the increasing complexity of JavaScript applications. It helps you package, compile, and manage the many resource files and dependency libraries that your project needs.

Webpack supports CommonJS, AMD and ES6 module systems, and is compatible with a variety of JS writing specifications, can deal with the dependency between modules, so it has more powerful JS modularized functions, it can compress images, CSS, JS file syntax check, compression, compilation and packaging.

The characteristics of the webpack

  1. Works well for single-page applications
  2. At the same time supportrequire()importThe module of grammar
  3. Allow very cutting edgecode splitting(Code segmentation) feature
  4. Hot loading allows forThe React, Vue. JsAnd other similar frameworks are developed locally faster
  5. It is by far the most popular build tool

The disadvantage of webpack

  1. Not suitable forwebA beginner in development
  2. forCSS, pictures and other non-JSResource files need to be obfuscated first
  3. Documentation is not perfect
  4. There are great changes in the use of different versions

The installation

  1. Global installation:
NPM install webpack -g // Install global webpack-cli NPM install webpack -g // Install global webpack-cli NPM install webpack -gCopy the code

Basic WebPack applications

SPA (Single Page Web Application) is a typical application for WebPack packaging

For example, the main parts are:

The JS file may contain multiple JS files, which can be merged and packaged into one file by WebPack. The CSS file may contain multiple CSS files, which can be merged and packaged into one file by WebPack. The image can be compressed and optimized by WebPackCopy the code

Example:

//a.js var run=function(){ console.log("aaa"); }; //module.exports.run=run; //module.exports.run=run; //ES6 syntax export default {run};Copy the code
//b.js var play=function(arg){ console.log(arg); }; // module.export.play =play; // module.export.play =play; //ES6 syntax export default {play};Copy the code
//var a=require("./a.js"); // require("./a.js"); //var b=require("./b.js"); //ES6 import js module import a from "./a.js"; import b from "./b.js"; var txt = "hello world"; a.run(); b.play(txt);Copy the code

Dist folder (to store the files after packaging, you can not create first, can be automatically created when packaging) -dis,dist,bulit

Packaging:

webpack --mode development
Copy the code

Configuration File Introduction

The default configuration file name is webpack.config.js

The core concept

The basic structure of a configuration file is as follows:

Exports ={// export entry:"....." , // Output configuration output:{...... }, // Module: {...... // resolve: {...... }, // plugins:[......] , // devServer devServer:{...... }};Copy the code
The default entry file is./ SRC /index.js. Output The output defines the exit file. The default exit file is: ./dist/main.js resolve Plugins that enable WebPack to handle non-javascript modules extend WebPack functionality to devServer development servers for configuring webpack-dev-server optionsCopy the code

Set the configuration file to auto complete:

// WebPack is built on node, Exports ={// export configuration output:{path:__dirname +'/dist', // export configuration output:{path:__dirname +'/dist', // output directory __dirname: path to the disk where the file is located (node global) filename:'js/main.js' // filename (can have subdirectories)}};Copy the code

Modify the webpack.json file

In webpack.json under “scripts” add:

"scripts": {  
    "dev": "webpack --mode development",
    "build": "webpack --mode production"  
  },  
Copy the code

Perform packaging

npm run dev
Copy the code

Entry and output

  1. Entry Entry configuration refers to the entry file on the page. Which file to start the package from. The default entry file is./ SRC /index.js

  2. /dist/main.js (); /dist/main.js ();

Path output path filename output filenameCopy the code

Example:

/ entry/entrance: {index: '. / SRC/js/main. Js',}, / / output output: {path: __dirname + "/dist",// where the packed file is stored filename:"main.js"Copy the code

module

Webpack can only package JS files (it only understands JavaScript syntax), and it cannot recognize files with other syntax. If you want webPack to package other files, you first need to make WebPack recognize different files, which requires special modules, collectively called loaders.

Loader classification

Convert to compile Script-loader, Babel-Loader, TS-Loader, coffee loader, handle style-loader, CSS-Loader, less- Loader, Sass - Loader, Postcss-loader Processing files raw-- Loader, URl-loader, file-loader processing data CSV-Loader, XML-Loader processing template language HTmL-Loader, pug-Loader, Jade - Loader, Markdown - Loader clean up and test mocha- Loader, ESlint-LoaderCopy the code

Commonly used loader

Css-loader parses the CSS statement style-Loader parses the text by csS-Loader, Add the <style> tag babel-Loader converts the ES6+ and JSX syntax to the ES5 earlier version syntax url-loader UrL-Loader converts the image that is not set or less than the limit byte to the base64 format for the image that is greater than the limit The image of byte is parsed by file-loader. The file-loader parses the URL of the project to import (including the URL of img SRC and background) and changes the reference path of the file after packaging. Vue has also launched its own Vue-Loader, which makes it easy to package.vue files in the vue-CLI (scaffolding for quickly building single-page applications).Copy the code

css loader

//index.js import a from "./a.js"; import b from "./b.js"; var txt = "hello world"; a.run(); b.play(txt); Import "./style.css"; // Note: this is a relative pathCopy the code

Install loader (loader is also a dependency package, which needs to be installed)

npm install css-loader --save-dev
npm install style-loader --save-dev
Copy the code

Define the CCS configuration in module:

Module: {rules: [{test: /. CSS $/, // re // add CSS to the style tag. ['style-loader','css-loader'], //loader or use exclude: /node_modules/, // regular exclude node_modules/}]},Copy the code

babel loader

Babel is a JS compiler that supports the latest versions of JavaScript (including new syntax such as JSX, TypeScript, etc.) through a syntax converter. These plug-ins allow you to use new syntax immediately without waiting for browser support.

To use Babel, you first configure the.babelrc file, which is used to set transcoding rules and plug-ins (json format), and is stored in the project root directory.

Tips: On Linux systems, files ending in rc usually represent files, configurations, and so on that are automatically loaded at run time.

In the.babelrc configuration file, you configure presets and plugins. . Babelrc configuration files are generally as follows:

{" presets ": [[" env" {} "modules" : false] / / modules are configuration items], "plugins" : [[" transform-Runtime ",{"polyfill":false}] // Polyfill is a configuration item]}Copy the code

The compiler is not responsible for translating new apis and global objects.

Plugins control how code is converted. Babel only converts new JS syntax by default, but not new APIS

plugins

Plugins can extend webPack functionality, and plugins can do anything the Loader can’t do.

For example, HtmlWebpackPlugin simplifies the creation of HTML files. You can generate an HTML file from a template file

resolve

Configure how WebPack finds the corresponding file for a module.

Resolve: {alias: {"@": resolve: {alias: {"@": resolve: {alias: {"@": Path. The join (__dirname, ". / SRC ") / / SRC directory, the project root directory mapping for @}, extensions: [", "json" js "]}Copy the code

Examples of other configuration items:

Devtool will generate and how to generate sourcemap DevServer Enable a local development server watch to listen for file changes and automatically package watchOption to customize watch mode option performance How does the command line display the performance prompt after packaging? If the size exceeds a certain size, is it a warning or an errorCopy the code

webpack-dev-server

Webpack-dev-server is a small Web server that can automatically monitor the changes of project files and automatically refresh the browser. Its HMR (Hot Module Replacement) method only replaces the updated part instead of reloading the page, greatly improving the refresh efficiency.

Webpack and webpack-cli NPM install webpack --save-dev NPM install webpack-cli --save-dev NPM install webpack-cli --save-dev NPM install webpack-dev-server --save-devCopy the code

Webpack.config.js configuration file:

let path=require("path"); // let HtmlWebpackPlugin=require('html-webpack-plugin'); Let htmlPlugin=new HtmlWebpackPlugin({filename:"index.html", template:__dirname+"/ SRC /index_temp.html", // Template file minify:{// compress removeComments:true, // delete the comment collapseWhitespace:true // merge the Spaces},}); // export configuration item module.exports = {// export entry:'./ SRC /js/main.js',// output: {path: __dirname + "/dist", // where the package is stored filename:"main.js", // module: {rules: [{test: Use: ['style-loader','css-loader'], exclude: ['style-loader','css-loader'], exclude: // node_modules/, // regular must include exclude!!}, {test: /\.js$/, use: 'babel-loader', exclude: // node_modules/, // exclude!!},]}, // resolve: {alias: {"@": Path. The join (__dirname, ". / SRC ") / / SRC directory, the project root directory mapping as the "@"}, extensions: [' js', 'json']}, / / development server devServer: {inline:true, // Support dev-server auto-refresh port:"8080", // Port open:true, // Automatically open the default browser},}Copy the code

Webpack-dev-serve. CMD is defined in the.bin directory

"scripts": {
    "dev": "webpack-dev-server --hot",
    "build": "webpack --mode production"
}
Copy the code

run

npm start
Copy the code

vue

The MVC pattern

The MVC pattern is one of the most widely used software architectures, forcing applications into three parts: Model, View, and Controller.

The MVVM pattern

MVVM mode is to change the MVC mode Controller to ViewModel. Changes to the View automatically update the ViewModel, and changes to the ViewModel are automatically synchronized to the View.

Basic grammar

Example:

The EL mounts the Vue instance to the DOM element, binds the HTML element data object with the ID, the Vue instance data (note: the data does not have the same name as the methods method), and the Methods event object, which contains the function to be triggered by the event (note: Do not name the method as the data in data.) Computed properties Watch Directives Custom hook functions (8) Hook functions The route component triggers the Components component container template to define a template, which can be a string. The selector props is used to receive data from the parent componentCopy the code

Instance properties/methods

$data Vue's data configuration item v. $options Specifies the props object v. $parent received by the current component $children Direct child of the current instance vm.$refs Native DOM element or child component registration reference information vm.$Slots is used to access content distributed by slots Vm.$store vuex status object (vuex plugin)Copy the code

methods

$emit() child component can set the properties of the object by using the alias of the parent component's custom event VM.$set() Vue. $watch listens for data changes.$on() listens for custom events on the current instance. Events can be triggered by vm.$emit. The callback function receives any additional arguments passed to the event-firing function. Vm.$mount can be manually mounted using vm.$mount() (Vue instantiates without the EL option). Vm.$destroy completely destroys an instance. Clean up its connections to other instances and unbind all its instructions and event listeners. Triggers hooks for beforeDestroy and Destroyed. <br />v-bind :class=""Copy the code

The life cycle

Four phases: create → mount → Update → destroy

BeforeCreate Before creating the created instance Initialize data after creating the created instance (Ajax data request, Obtains the Vuex status and route switching.) beforeMount Before loading Mounted After DOM operation (third-party plug-ins are applied) beforeUpdate Before updating Data is modified through events, v-Model causes changes, AJAX asynchronously updates data before destroying the instance and switching routes after destroying the instance (the component will be destroyed).Copy the code

Calculate attribute

Accessing a evaluated property multiple times immediately returns the previous evaluated result without having to execute the function again.

Calculated properties have caching

The array is checked for updates

Push (), pop(), shift(), unshift() splice(), sort(), reverse() mutating methods that trigger view updates filter(), concat(), and slice() nonmutating methods, They can return a new array without triggering view updates, and they can refresh the view by replacing the old array with the new arrayCopy the code

The event object

Event.type type of event triggered event.target HTML element of event triggered event.preventdefault () preventDefault behavior of event event.stoppropagation () prevent event bubblingCopy the code

Vue components

  1. Create components
Let myTemp={template:'#temp', // id id: Function (){// must be a function(closure) return {// must return an object {} title:"dadaqianduan"}}Copy the code
  1. Certified components
Let app=new Vue({el:"#box", Components: {myTemp}}); Vue.component('myTemp', myTemp) can also be used for global registration.Copy the code
  1. Using the component
<! <div id='box'> <! - component name if use hump definition, to dash name - > < my - temp > < / my - temp > < / div >Copy the code
  1. Event communication
  • Data operations between parent and child components are performed throughpropsProperties and$emit()Method

Routing using

Route definition includes route path, route name, and route component object.

Routes: [{path: '/', // route name: 'home', // route name: 'home', // route name: 'home', // route name: 'home'}, {path: '/users', name: 'Users', component: UserComponent }, { path: '/about', name: 'about', component: () => import( './views/About.vue') } ]Copy the code
  1. Dynamic routing
routes: [
  {
    path: '/users/:username/post/:postid',
    name: 'Users',
    component: UserComponent,
  }
]
Copy the code
/user/:username	
/user/tom	
{username:'tom'}

/user/:username/post/:postId	
/user/tom/post/3	
{username:'tom',postId:'3'}
Copy the code

Routing navigation

  1. Route navigation guard

What is a routing navigation guard can be simply understood as a lifecycle callback function for the routing component.

BeforeRouteEnter (to, from, next) {// to: indicates the routing component to be entered // from: // next: Next (function(app) {// after entering the current component, use this to retrieve the instance of the current component. Get ('/users/' + app.id).then(res => {app.user = res.data.data; }); }); } beforeRouteUpdate(to, from, next) {// In this case, we can use this to indicate the current component object const app = this; Route axios.get('/users/' + to.params.id).then(res => {app.user = res.data.data; }); // Execute next(); }Copy the code
  1. Programmatic routing navigation
Methods: {the login () {if landing (success) {/ / jump this page. $router. Push ('/'); }}}Copy the code
  1. push()

Jumps to the specified routing address and writes the current address to history. The argument can be a string path or an object describing the address information

String router.push('home') object router.push({path:'home'}) Named route router.push({name:user,params:{userId:1}})Copy the code
  1. Replace () : Jumps to the specified route, which does not add a new record to history, but replaces the current history record.

  2. Global route navigation guard

Example:

// Global routing navigation guards router.beforeEach((to, from, next) => {});Copy the code

Embedded routines by

Children: [{path: "", component: route name}, {path: "path name ", component: route name}]Copy the code

Named view

Using

, you can use the name attribute to set the name of the view. That is, the view of named routes is short for named view.

Example:

<router-view/> 
<router-view name="content"></router-view> 
import About from './views/About.vue';
routes: [  
{
  path: "/about",
  name: "about",
  components: {
    default: About,
    content: UserComponent
  }
}
]
Copy the code

Look back at my previous highly praised articles, maybe you can harvest more oh!

  • Vue.js pen questions to solve common problems in business
  • Vue front-end development tutorial notes
  • Dada front end personal Web share 92 additional answers to interview questions in JavaScript
  • [Illustrated, like collection oh!] Re-study and consolidate your Vuejs knowledge
  • [Mind Mapping] Front-end development – Consolidate your JavaScript knowledge
  • 14 – even liver 7 nights, summed up the computer network knowledge! (66 in total)

❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create better articles

Like, bookmark and comment

I’m Jeskson, thanks to all the talented people: likes, favorites and comments, we’ll see you next time! ▌ I have to show you the truth. ▌ I have to show you the truth. I have to show you the truth.

See you next time!

The article continues to be updated, you can search A wechat “programmer Doraemon” the first time to read, reply [data] I prepared for the first line of big factory data, this article www.dadaqianduan.cn/#/ has been included

Welcome to Star: github.com/webVueBlog/…