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
html
Label is made<>
Surround the key words.html
Tags usually come in pairs, with an beginning tag and an end tag.- Some labels have no closing tags and are single labels. Single labels must be used
/
At the end. - All the content of the page is there
html
Tag. html
A tag is divided into three parts: tag name, tag content, and tag attributes.html
Tags 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.- The content of a tag is the content inside a pair of tags.
- The contents of a tag can be other tags.
Tag attributes
class
Attribute: The class name used to define the elementid
Attribute: Used to specify the uniqueness of an elementid
, the value of the property is in the entirehtml
Uniqueness in the documentstyle
Property: specifies the inline style of an element. Using this property overrides any global style Settingstitle
Attribute: Additional information used to specify an elementaccesskey
Property: Specifies the shortcut key that activates the elementtabindex
Attribute: Used to specify where the element istab
Order under the keydir
Attributes: Used to specify the text orientation of the content in an element. Attributes have onlyltr
orrtl
Two kinds oflang
Attribute: The language used to specify the content of an element
Event attributes
window
Window event,onload
Is triggered after the page has finished loading,onunload
Occurs when the user leaves the page (click to jump, reload the page, close the browser window, etc.)form
Form events,onblur
When the element loses focus,onchange
When the element’s value is changed,onfocus
When the element gets focus,onreset
Is triggered when the reset button in the form is clicked,onselect
Is triggered when the element text is selected,onsubmit
Triggered when the form is submittedkeyboard
Keyboard events,onkeydown
Is triggered when the user presses a key,onkeypress
Is triggered when the user presses the key. This property does not apply to all keys.alt,ctrl,shift,esc
mouse
Mouse event,onclick
Is triggered when a mouse click occurs on an element,onblclick
Is triggered when a double mouse click occurs on an element,onmousedown
Is triggered when the mouse button is pressed on the element,onmousemove
Is fired when the mouse pointer moves over the element,onmouseout
When the element pointer moves out of the element,onmouseup
Triggered when the mouse button is released on the element.Media
Media events,onabort
Is triggered when exiting,onwaiting
Triggered when the media has stopped playing but intends to continue playing.
Text labels
- Paragraph tags
<p></p>
Paragraph tags are used to describe a piece of text - 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 - Emphasize statement tags,
<em></em>
Used to emphasize the importance of certain words - More emphasis on labels,
<strong></strong>
and<em>
The tag is used to emphasize text, but to a greater degree - No semantic tags
<span></span>
, the tag has no semantics - Short text reference tags
<q></q>
“, a quote of short text - Long text reference tags
<blockquote></blockquote>
To define long text references - Wrap the label
<br/>
Multimedia label
- Link tags,
<a></a>
- Picture tag,
<img/>
- Video tag,
<video></video>
- Audio label,
<audio></audio>
The list of
- 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 - Ordered list,
ol,li
- Define the list,
<dl></dl>
, define the list usually and<dt></dt>
and<dd></dd>
Tag together
form
- Table label
<table></table>
- A row of tables
<tr></tr>
- The head of a table
<th></th>
- The cell
<td></td>
- Table merge, the same row, merge several columns
colspan="2"
Merge several rows in the same columnrowspan="3"
The form tag
- 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
- 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
- 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
- box
<div></div>
- Page header
<header></header>
.html5
Added semantic tags to define the head of the page, mainly used for layout, split the structure of the page - At the bottom of the information
<footer></footer>
.html5
Added semantic tags to define the bottom of the page, mainly used for layout, split the structure of the page - navigation
<nav></nav>
.html5
Added semantic tags that define a navigation, mainly for layout, to split the structure of the page - The article
<article></article>
.html5
Added semantic tags that define an article and are mainly used for layout, splitting the structure of the page - The sidebar
<aside></aside>
, semantic tags, define information outside of the topic content, mainly used for layout, split the structure of the page. - Time stamp
<time></time>
, semantic tags, define a time
The web structure
<! DOCTYPE html>
Define a document type that tells the browser which standard to interpretHTML
<html></html>
Can tell the browser itself is aHTML
The document<body></body>
The content between the tags is the main content of the web page<head></head>
The tag is used to define the header of the document and is the container for all header elements<title></title>
The element defines the title of the document<link>
The label willcss
Style file links toHTML
In the file<meta>
Define the metadata of the document
Module partition
- Common enterprise website, more by the head area, display picture area, subject area, the bottom of the information area
- The principles of splitting web pages are as follows: – Top to bottom – inside to out
CSS Code Syntax
CSS
Cascading Style sheets(Cascading Style Sheets)
It is mainly used for definitionHTML
The style in which content is displayed in the browser, such as text size, color, bold font, etc.css
Code is usually stored in<style></style>
tagcss
Styles consist of selectors and declarations, which consist of properties and values- selector
{attribute: value}
- Selectors: Also known as selectors, indicate the elements in a web page to which style rules should be applied
CSS Placement
- Inline styles are not recommended
- Inline style sheets
- External style sheets
CSS inheritance
CSS
Inheritance is a rule that allows styles to apply not only to a particular HTML tag element, but also to its descendants.- 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
- 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
- Label selector: Modify by label name
css
style - Wildcard selector: Selects all the elements in the page
- Attribute selector
- Descendant selector: Selects all elements below a parent element
- 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
id
Selector: Passedid
Find the unique tag on the pageclass
Selector: by specificclass
Class to find the corresponding tag on the page to.class
The name of the- Pseudo-class selector:
:hover
Mouse over an element;:before
Insert content before an element;:after
Insert content after an element - Group selectors: You can set the same style for multiple different selectors
The priority of the selector
- When there are different selectors that style the same object, and two selectors that have the same property are assigned different values.
- Which selector style to apply by calculating which selector has the highest weight
- 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
- The background color
background-color
- The background image
background-image
background-image:url(bg01.jpg);
Copy the code
- Background Image location
background-position
background-position:10px 100px; // represents the x and y axesCopy the code
- Background image repetition
background-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
- Background image positioning
background-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
background
abbreviations
background:#ff0000 url(bg01.jpg) no-repeat fixed center
Copy the code
Font style
- Font family
font-family
Font-family :" Microsoft Yahei "," black ";Copy the code
- The font size
font-size
font-size:12px;
Copy the code
The default font size for web pages is 16px
- The font size
font-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
- The font color
color
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
- The italic font
font-style
Font-style :italic normal Text-oblique text-oblique displayCopy the code
Text attributes
- Line height
line-height
line-height:50px;
Copy the code
You can prop up the height of the parent element
- Horizontal text alignment
text-align
Left Align the text to the left. Center Center the text. Right Align the text to the rightCopy the code
- Vertical alignment of text line height
vertical-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
- Text indentation
text-indent
text-indent:2em;
Copy the code
Usually used to indent the first line at the beginning of a paragraph
- The space between letters
letter-spacing
- Spacing between words
word-spacing
- Case of text
text-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
- Embellishment of text
text-decoration
None by default. Underline underline. Overline Indicates the crossed line. The line - through the midline.Copy the code
- Word wrap
word-wrap
word-wrap: break-word;
Copy the code
Basic styles
- The width of the
width
width:200px; Defines the width of the elementCopy the code
- highly
height
Height :300px By default, the element has no heightCopy the code
- The mouse style
cursor
Define the style cursor:pointer for the mouse
Default Default pointer Small hand shape move move shapeCopy the code
- transparency
opacity
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
- visibility
visibility
visibility:hidden; When used in table elements, this value removes a row or column without affecting the layout of the table.Copy the code
- Overflow hidden
overflow
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
- Border color
outline
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
- 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.
- Element classification conversion
display
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
- stroke
border
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
- spacing
margin
div{margin:20px 10px 15px 30px; }Copy the code
- Fill in
padding
padding:10px
Copy the code
Float float
- 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.
- 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
- Using pseudo class to achieve clear floating
.clearFix {
content="";
display:block;
width:0;
height:0;
clear:both;
}
Copy the code
Locate the position
- The positioning function can make the layout more free.
- 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.
- 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.
- 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
- 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
- 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
- Solve cross-browser, cross-platform issues
- To enhance the
web
Application 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
- 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).
- Property selector
E[attribute^=value]
Used to select an element with an attribute value beginning with the specified valueE[attribute$=value]
Used to select the element whose attribute value ends with the specified valueE[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
- Pseudo-class selector
:root
Select the root element of the document, in HTML, always<html>
The element:last-child
Adds 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-child
Adds a style to an element that is the only child of its parent element:first-of-type
Adds a style to an element that is the first element of its type and sibling:last-of-type
Adds 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-type
Adds a style to an element that is unique among elements of the same type and sibling:empty
Adds styles to elements that have no child elements, including text content
- Pseudo-element selector
:enabled
Adds a style to an element that is currently available, usually to define a style for a form or a hyperlink:disabled
Adds a style to an element that is currently unavailable, usually to define a style for a form or a hyperlink:checked
Adds a style to the element that is currently selected:not(selector)
To notselector
Adds styles to the elements of the:target
Adds a style to the anchor point target element being accessed::selection
Adds a style to the element where the user is currently selecting content
CSS3 Added attributes
- Add background attribute
background-clip
Set the background coverageborder-box/paddingbox/content-box
background-origin
Sets the starting point of the background overlayborder-box/paddingbox/content-box
background-size
Set the background sizeCover /contain/ contain/ contain
- New font text-related properties
text-overflow
Sets what to do when text overflows the element boxclip/ellipsis
word-wrap
Specifies how words are newlinenormal/break-word
word-break
Specifies how to wrap linesnormal/break-all/keep-all
- Added box model properties
box-shadow
shadowh-shadow v-shadow <br />blur spread color inset
resize
Adjust the sizenone/both/horizontal
outline-offset
The offset of the contourlength/inherit
Added deformation animation properties
transform
translate(x,y)
rotate(angle)
scale(x,y)
skew(angleX ,angleY)
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
transform 3D
function
Transform adds three transform functions:
rotateX
: indicates that the element is alongx
Shaft rotation.rotateY
: indicates that the element is alongy
Shaft rotation.rotateZ
: indicates that the element is alongz
Shaft rotation.
-
Transform-style is used to set the effect of nested child elements in 3D space.
-
Perspective is set to the perspective effect, the perspective effect is near large, far small.
-
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%.
-
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-delay
Set the delay time for the transitiontransition-duration
Set the transition time for the transitiontransition-timing-function
Set the time curve for the transitiontransition-property
Which setting.CSS
Use the transitiontransition
One declaration sets all transitional properties
CSS3 animation properties
animation
@keyframes
Define the animation selectoranimation-name
use@keyframes
Defined animationanimation-delay
Sets the duration of the animationanimation-timing-function
Set the time curve of the animationanimation-iteration-count
Set the number of times the animation is playedanimation-direction
Set the animation to play backwardsanimation-play-state
Set the animation playing statetransition
One declaration sets all animation properties
CSS3 adds new column attributes
column-count
Sets the number of columns the element should be separated fromcolumn-width
Sets the width of the columncolumns
A declaration sets the column width and number of columnscolumn
column-gap
Sets the interval between columnscolumn-span
Sets the number of columns that the element should spancolumn-rule-style
Sets the style for spacing between columnscolumn-rule-color
Sets the color of the interval between columnscolumn-rule-width
Sets the width of the interval between columnscolumn-rule
One 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 pixelsem
: Relative unit. The reference point is the font size of the parent node, if definedfont-size
By itself (the default browser font is16px
), the entire page1em
It’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 nodehtml
To calculate the font size,CSS3
Add new properties.%
:%
Percentage, a unit of relative length, the percentage value relative to the parent elementVw, VH, Vmin, vmax
Mainly 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: vw
andvh
The middle and smaller one.Vmax: vw
andvh
The larger of the medium.
Elastic box model
Basic grammatical concepts of elastic box model
Any container can specify an elastic layout
JavaScript
JavaScript based
- External introduction
js
File: Approved<script src="main.js"></script>
- keywords
- Variable names are case sensitive
- Naming conventions
JavaScript data types
- string
(String)
- digital
(Number)
- Boolean value
(Boolean)
- 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
- object
(Object)
Js has the following built-in objects:
Object
Is the superclass (base class) of all JS objects. All objects in JS are inherited from ObjectArray
An array object defines array properties and methodsNumber
Digital objectsBoolean
Boolean object Boolean value correlationError
Error object handler errorFunction
Function objects define function properties and methodsMath
Mathematical objectsDate
The date objectRegExp
Object Regular expression objects define text matching and filtering rulesString
String objects define string properties and methods
Arithmetic operations
var y = 3;
Copy the code
Casts.
- String to number
parseInt() parseFloat() isNaN()
- Number to string
toString()
The assignment operation
- Compound assignment operator
+= -= *= /= %=
Relationship between operation
- Relational operations:
> < <= >=! === === == and ===! = and! = =
"=" "==" "==="
What’s the difference?
=
Is an assignment symbol= =
Ignore the datatype to determine equality= = =
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:
if
statements - Dual branch selection:
if-else
statements - Multiple branch statements:
if-else if-else
statements
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-while
Is to execute the body of the loop first and then check the loop condition.do-while
Ensures 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
break
Exit the loopcontinue
Skip this loop and continue the next one
An array of
- To define an array
var arr = new Array();
var arr = [];
Copy the code
- Definition in a literal way
var arr = ["1","2"];
Copy the code
- Assign values to arrays
arr[0] = "1";
arr[1] = "2";
alert(arr[0]+","+arr[1]);
Copy the code
- Array index
arr[0]+","+arr[1]
Copy the code
- The length of the array
// Syntax arr.length // Index of the last element arr.length-1Copy the code
Array methods
indexOf
An array can be searched for the location of a specified element by using indexOf(), returning -1 if not found
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
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
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
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
sort
Sort () sorts the current array
var arr = ["b","c","a"]; arr.sort(); arr; //["a","b","c"]Copy the code
reverse
Reverse () drops the elements of the entire array
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
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
- String attribute
length
– The length property of the string slice()
Slice (start[,end]), start-- start index end-- end indexCopy the code
substr()
Substr (start[,length]), start: start. The value is a length characterCopy the code
split()
Split ([separator[,limit]]), splits the string conditionally, returning an array
indexOf()
The first occurrence in the parent string, starting at 0! Negative 1 is not returned
lastIndexOf()
Reverse lookup
charAt(index)
CharAt (index) Specifies the index character
toLowerCase()
Turn to lowercase
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
test
methods
Retrieves the specified value in the string.
exec
methods
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
Object
Is the superclass (base class) of all JS objects. All objects in JS are inherited from ObjectArray
The array objectNumber
Digital objectsBoolean
The Boolean objectError
Error objectFunction
The function objectMath
Mathematical objectsDate
The date objectRegExp
Object Indicates the regular expression objectString
String object
Math methods
abs()
Absolute value (minus plus and minus)random()
The random number,0-1
Between random numbers,1
There will be noround()
roundedfloor(x)
Round down (round down)ceil(x)
Round up (round up)max(x,y)
X and y
The maximum ofmin(x,y)
X and y
The minimum value incos(x)
x
The cosinesin(x)
x
The sinesqrt(x)
returnx
The square root ofPow (3, 4)
return3
the4
To the power
The Date methods
getFullYear()
Year of Return (4th)getMouth()
Return month (0–11)getDate()
Return dategetDay()
Return Week (0-6)getHours()
Returns the hourgetMinutes()
Returns the minutesgetSeconds()
Return to the secondgetTime()
Returns the number of milliseconds between midnight, January 1, 1970, and the specified date (string)setFullYear()
Set the datesetMouth()
Set the monthsetDate()
Set the daysetHours()
Set hourssetMinutes()
Set the minutessetSeconds()
Set up the secondsetTime()
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
- A class is an abstract concept
- Object: something concrete
- A class is an abstraction of an object, which is a concrete instance of a class
- Classes do not take up memory; objects take up space
- Object to declare the object
- Traversal objects –
for in
cycle
Define the object
- Literal creation
- The factory pattern
Function Cat(n,c){return {name:n, color:c, say:function(){alert("dadaqianduan")}}Copy the code
- 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
Javascript
It also provides oneinstanceof
The 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
constructor
Is 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
- in
JavaScript
A stereotype is an object. The function of a stereotype is to implement object inheritance. - in
JavaScript
There is a property,prototype
, which corresponds to the stereotype of the current object. - All of the
JavaScript
Object, 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
- All reference types have one
__proto__
attribute - All functions have one
prototype
attribute - 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
__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.
- 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
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
constructor
The 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
- All reference types (functions, arrays, objects) are owned
__proto__
Properties. - All functions have
prototype
Properties. - 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
.null
There 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).
- Creating an object is often a complex process, so it is not appropriate in a complex object.
- 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:
- The singleton pattern is a common pattern. There are some objects that we need only one, such as the global cache and the browser
window
Object. - 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
- 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
- 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
- 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
return
Only one data can be returned- If it’s not in the function
return
, 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 function
return
To 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
- You can read variables inside other functions
- 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 boxconfirm()
A prompt box with a confirm cancel buttonprompt()
A prompt box with a text field that can be enteredsetInterval()
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 millisecondsclearInterval()
Clearance interval timerclearTimeout()
Clearing the Timeout TimerrequestAnimationFrame
Frame 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()
forwardwindow.history.back()
back
The location positioning
window.location.href='http://www.baidu.com/'
Page jumpwindow.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)
throughid
To obtainDOM
Object (object)getElementsByTagName(tag)
Obtain by labelDOM
Object (” array-like “object)getElementsByName(name)
throughname
To obtainDOM
Object (” array-like “object)getElementsByClassName(class)
throughclass
To obtainDOM
Object (not supported in IE8 below)
Manipulate relationships between DOM
createElement(tag)
Create the elementThe removeChild (object)
Remove elementsThe appendChild (object)
Insert elementsReplaceChild (Replacement object, replaced object)
Replace the elementInsertBefore (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 propertiesgetAttribute
Retrieve attributesremoveAttribute
Delete attributes:hasAttributes
Determines whether the attribute exists (returnedture/false
)
The event
var oDiv=document.getElementById('box');
oDiv.onclick=function(){
alert('hello world');
};
Copy the code
addEventListener( )
Adding event listeningremoveEventListener( )
Deleting an Event Listener
Event classification
window
The event
onload
Load (when a page or image is completed)onunload
User exit pageonresize
The window or frame is resizedonscroll
Scrollbar 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
- Object’s default behavior
- Prevent default behavior:
event.preventDefaut()
Flow of events
Event flow direction: capture → event target → bubble
- Event capture
- Event goals
- 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
id
The selector
$('#box')
Copy the code
class
The 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
- 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
- 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
- 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
- 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
- replace
ReplaceAll () replaces all matched elements in a selector with the specified HTML or DOM elementCopy the code
- delete
Empty () removes all child nodes in the set of matched elements. Remove () removes all matched elements from the DOMCopy the code
- 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
- First, the client and server need to establish a connection.
- 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. - 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 Code
Status code), afterServer Information,Entity informationAnd possible content. - 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
- use
image
object
<img src="" style="display:none"/>
Copy the code
- use
image
object
var image = new Image();
image.src="";
Copy the code
- use
XMLHttpRequest
object
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
- Code is separated from structure
- The separation of style and structure
- Data is separated from code
AMD: Asynchronous Module Definition
That 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
- merge
JavaScript
Code, use as little as possiblescript
The label. - Clog-free loading
JavaScript
. - Dynamically create
script
Tag 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
- Works well for single-page applications
- At the same time support
require()
和import
The module of grammar - Allow very cutting edge
code splitting
(Code segmentation) feature - Hot loading allows for
The React, Vue. Js
And other similar frameworks are developed locally faster - It is by far the most popular build tool
The disadvantage of webpack
- Not suitable for
web
A beginner in development - for
CSS
, pictures and other non-JS
Resource files need to be obfuscated first - Documentation is not perfect
- There are great changes in the use of different versions
The installation
- 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
-
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
-
/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
- Create components
Let myTemp={template:'#temp', // id id: Function (){// must be a function(closure) return {// must return an object {} title:"dadaqianduan"}}Copy the code
- Certified components
Let app=new Vue({el:"#box", Components: {myTemp}}); Vue.component('myTemp', myTemp) can also be used for global registration.Copy the code
- Using the component
<! <div id='box'> <! - component name if use hump definition, to dash name - > < my - temp > < / my - temp > < / div >Copy the code
- Event communication
- Data operations between parent and child components are performed through
props
Properties 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
- 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
- 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
- Programmatic routing navigation
Methods: {the login () {if landing (success) {/ / jump this page. $router. Push ('/'); }}}Copy the code
- 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
-
Replace () : Jumps to the specified route, which does not add a new record to history, but replaces the current history record.
-
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/…