Front end learning
Learning route
- **HTML5 basics * *: mainly learn the most common incompatible HTML tags
- CSS3 Foundation: there is no compatible CSS style. Use the learned tags to complete the traditional WEB page layout
- H5C3 improvement: learn new HTML tags and CSS styles.
- **Introduction to Java Script * *: variables, data types, common functions, etc
HTML related knowledge
-
Webpage
-
Website: refers to a collection of web pages on the Internet that are made using HTML to display specific content according to some rules
-
Web page: a "page" in a website, usually an HTML file, which should be read through a browser
-
Web page is the basic element of a website, which is usually composed of pictures, links, text, sound and video. Web pages are usually html,. htm, so it is commonly known as HTML file
-
HTML: hypertext markup language (Hyper Text Markup Language, which has two meanings beyond text limit and hyperlink text). It is a markup language used to describe Web pages. Markup language is a set of markup tags.
-
Formation of web pages: Web pages are composed of elements, which are described by html tags, and then parsed and presented by browsers.
-
Output: Label
<img src="1.jpg">
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kTEAMqXw-1627031876317)(C:\Users \ Monday Hao \ appdata \ roaming \ typora \ typora user images \ image-20210717160645566. PNG)]
-
-
browser
-
Browser kernel: also known as rendering engine, it is responsible for reading web content, sorting messages, calculating the display mode of web pages and displaying pages.
browser kernel remarks IE Trident IE, cheetah, 360, baidu browser kernel firefox Gecko Firefox browser kernel Safari Webkit Apple browser kernel Chrome/Opera Blink Chrome, Opera browser kernel and Blink are actually branches of Webkit Some domestic browsers Webkit/Blink UC
-
-
WEB Standard
-
That is, the collection of a series of standards formulated by WC organization and other standardization organizations. W3C (World Wide Web Consortium) is the most famous international standardization organization.
-
Benefits:
- Let the pages precipitated by different developers be more standard and unified
- Make the development prospect of Web more broad
- Content can be given to a wider range of equipment houses
- Easier to be searched by search engines
- Reduce website traffic costs
- Make the website easy to maintain
- Improve page browsing speed
-
Composition: Structure, Presentation and Behavior.
standard explain structure Sorting and classifying the elements of Wang's web page, mainly learning html performance Set the layout, color, size and other appearance styles of web elements, mainly learning CSS behavior Behavior refers to the definition of web page model and the preparation of interaction, mainly learning JavaScript
-
HTML tags
grammatical norm
- Basic specification: Keywords surrounded by angle brackets, for example. Usually, tags appear in pairs, which are called Double tags. For example, one is the start tag and the other is the end tag. Occasionally there is a single label, such as
- Label relationships: include and juxtapose
Basic structure label
Each web page has a basic structure tag (also known as skeleton tag), which contains the basic content of the page
Tag name | definition | explain |
---|---|---|
< html >< /html > | Root label | |
< head >< /head > | ||
< title>< /title> | ||
< body>< /body> |
development tool
Common labels
Label properties (inline)
When making web pages with HTML, if you want the HTML tag to provide more information, you can use the properties of the HTML tag to set it.
<Tag name property 1="Attribute value 1" Attribute 2="Attribute value 2" ...> content </Tag name> <Phone color="gules" size="5 inch"> </mobile phone>
PS: the tag can have multiple attributes, which must be written in the start tag after the tag name.
There is no order between attributes. Tag names and attributes, attributes and attributes are separated by spaces.
Take the format of key value pair key = "value"
Typesetting label
It is mainly used with css to display the tag of web page structure. It is the most commonly used tag in web page layout.
Tag name | definition | explain |
---|---|---|
<h1~h6>,< /h1~h6> | Title label | |
| Paragraph label | HTML documents can be divided into several paragraphs |
Horizontal line label | ||
Wrap label | ||
| The text is displayed in bold | |
< b>< /b> | The text is displayed with a strikethrough | |
Text is underlined | ||
The text is displayed with a strikethrough | ||
Text is underlined |
Label (img image)
attribute | Attribute value | describe |
---|---|---|
src | URL | Image path |
alt | text | Alternate text when image cannot be displayed |
title | text | Display when mouse over |
width | pixel | Sets the width of the image |
high | pixel | Sets the height of the image |
border | number | Sets the width of the image border |
<img src="cz.jpg" width="300" height="300" border="3" title="This is a little dandelion" />
PS: when using width and high, the height / width will be adaptive to maintain the image scale. It is not recommended to use them together, which may cause the image to scale unsightly
Link label (img)
attribute | effect |
---|---|
href | Used to specify the url address of the link target, (required attribute) when the href attribute is applied to the tag, it has the function of hyperlink |
target | Used to specify the opening method of the linked page. The values are_ self and_ blank two, of which_ self is the default_ blank is the way to open in a new window. |
<a href="Jump target" target="Pop up method of target window">Text or image</a> target="_self" Default window pop-up method target="_blank" A new window pops up
Table label
Tables are mainly used to display data, not layout;
Tag name | definition | explain | |||
---|---|---|---|---|---|
| Table label | Used to define a table label, the outermost large box | |||
Row label | Used to define rows in a table, which must be nested in the table label | ||||
Cell label | Used to define cells in a table, which must be nested in | ||||
Header cell label | Generally, the header cell is located in the first row or column of the table, and the text is bold and centered. Only the header label is needed | ||||
Title label | Centered and displayed on the table, the caption label must follow the table label. | ||||
clospan and rowspan | Merge properties | Used to merge cells; Consolidation steps: first determine the consolidation method (cross row or cross column); In target cell | Write merge statements in the; Delete extra cells |
<table> <caption>I'm the table title</caption> <tr> <td>Text in cell</td> ... </tr> ... </table>
Table properties
Write it in the start tag of table. It is not commonly used in development and is often set through CSS;
Attribute name | Attribute value | meaning |
---|---|---|
border | Image value | Sets the border of the table |
cellsoacing | Pixel value (default = 2) | Sets the size of the blank space between the cell and the cell border |
cellpadding | Pixel value (default = 1) | Sets the size of the gap between the cell content and the cell border |
width | Pixel value | Sets the width of the table |
heigh | Pixel value | Sets the height of the table |
aligh**** | left\center\right | Set the horizontal alignment of the table in the web page |
The three parameters are 0. The three parameters border cellpadding cellspacing developed by us are 0
List label (ul\ol\dl)
-
Unordered list (ul)
-
< UL > < / UL > can only be nested
- , directly in
- And
- It is equivalent to a container that can hold all elements.
-
<ul> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> ...... </ul>
-
Ordered list (ol)
- The value of the type attribute in the < ol > tag is the sorted serial number. When the type attribute is not added, the ordered list starts sorting from the number 1 by default.
- The commonly used type attribute values are 1, a, a, I and I
- The reversed attribute enables the sequences in the list of sequences to be arranged in reverse order.
- The value of the start attribute is 3, and the first serial number in the ordered list will be arranged from 3.
<ol type="A" start="3" reversed="reversed"> <li>List item 1</li> <li>List II</li> <li>List III</li> </ol>
-
Custom list (dl)
Definition list is often used to explain and describe terms or nouns. There is no bullet before the list item of definition list.
<dl> <dt>Noun 1</dt> <dd>Noun 1 interpretation 1</dd> <dd>Noun 1 interpretation 2</dd> ... <dt>Noun 2</dt> <dd>Noun 2 interpretation 1</dd> <dd>Noun 2 interpretation 2</dd> ... </dl>
-
Comment Tag
<!-- Comment statement --> Shortcut keys are: ctrl + / perhaps ctrl +shift + /
**Team agreement: * * there is a space character before and after the comment content, and the comment is located above the code to be annotated, occupying a separate line
form
In HTML, a complete form is usually composed of form controls (also known as form elements), prompt information and form fields. The purpose of the form is to collect user information.
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-L14skQxP-1627031876320)(C:\Users \ Monday Hao \ Desktop \ first day of front-end foundation \ 640.png)]
Form control:
The input button, reset button, and check box of the form include the specific input items of the form.
Prompt:
A form usually needs to contain some explanatory text to prompt users to fill in and operate.
Form field:
It is equivalent to a container to hold all form controls and prompt information. It can define the url address of the program used to process form data and the method to submit data to the server. If the form field is not defined, the data in the form cannot be transferred to the background server.Input control (input)
input means that the label is a single label. The type attribute sets different attribute values to specify different control types
- Common attributes:
attribute Attribute value explain name User defined Form name. There are many forms in the page. Name is mainly used to distinguish different forms. value User defined The default text value in the input control; Form value, the default text displayed in the form size positive integer The width of the input control displayed on the page checked checked Define the default value of the selection control maxlength positive integer Maximum number of words allowed -
type attribute
Text (single line text input box); Password (password input box); Radio (radio button); Checkbox; Button (normal button); Submit button; Reset button; Image (submit button in image form); File (file domain)
user name: <input type="text" /> password:<input type="password" />
-
value attribute
Value is the default text value. Some forms want to display several words by default as soon as the page is opened, which can be set through this value.
user name:<input type="text" name="username" value="enter one user name">
- name attribute
Name is the name of the form, so that the form can be found in the background through the name attribute. There are many forms in the page. Name is mainly used to distinguish different forms.
-
- The value after the name attribute is defined by ourselves.
- If the radio is a group, we must give them the same name, so that we can choose one of them
- We use the name attribute less now, but it is necessary when we learn ajax and background.
<input type="radio" name="sex" />male <input type="radio" name="sex" />female
- checked property
Indicates the default selected status. It is more common in radio buttons and check buttons.
nature other: <input type="radio" name="sex" value="male" checked="checked" />male <input type="radio" name="sex" value="female" />female
Label label
- The label label defines the label (label) for the input element.
- The main purpose of label is to improve the user experience. Improve the best service for users.
**Function: * * used to bind a form element. When you click the label label, the bound form element will get the input focus.
How to bind elements
- The first usage is to use the label label to directly include the input form, which is suitable for single form selection
- The second usage, the for attribute, specifies which form element the label is bound to (by id).
First kind <label> user name: <input type="radio" name="usename" value="enter one user name"> </label> Second <label for="sex">male</label> <input type="radio" name="sex" id="sex">
textarea control (text field)
- You can easily create a multi - line text input box through the textarea control
- cols = "number of characters in each line" rows = "number of lines displayed" we don't need it in actual development
<textarea > Text content </textarea>
Difference between text box and text field
form name difference Default value display For scene input type="text" Text box Only one line of text can be displayed Single label, displaying the default value through value User name, nickname, password, etc textarea Text field Multiple lines of text can be displayed Double label. The default value is written in the middle of the label Message Board select drop-down list
- If there are multiple options for users to select, in order to save space, we can use the select control to define the drop-down list.
- When selected = "selected" is defined in option, the current item is the default selected item.
- We will use less in actual development
<select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> ... </select>
Form field
-
How to transfer the collected user information to the server?
-
- Through form fields
-
Purpose:
-
- In HTML, the form tag is used to define the form field to realize the collection and transmission of user information, and all the contents in the form will be submitted to the server.
<form action="url address" method="Submission method" name="Form name"> Various form controls </form>
Common attributes:
- Each form should have its own form field. When learning ajax background interaction later, you must need the form field.
attribute Attribute value effect action url address Specifies the url address of the server program that receives and processes form data. method get/post Used to set the submission method of form data. The value is get or post. name name Specifies the name of the form to distinguish multiple forms on the same page. The difference between GET and POST
- GET is harmless when the browser goes back, and POST submits the request again.
- GET requests will be actively cache d by the browser, but POST will not, unless manually set.
- GET requests can only be url encoded, while POST supports multiple encoding methods.
- The GET request parameters will be completely retained in the browser history, while the parameters in POST will not be retained.
- The size of the GET request is generally (1024 bytes). The http protocol has no limit, but it is related to the server and operating system. In theory, post has no size limit, and the http protocol specification has no size limit. In fact, the amount of data that can be transmitted by post depends on the server settings and memory size.
- For the data type of parameters, GET only accepts ASCII characters, while POST has no restrictions.
- GET is less secure than POST because parameters are directly exposed to the URL and cannot be used to pass sensitive information.
Team agreement:
- Element attribute values use double quotation mark syntax
- The element attribute value can be written
recommend <input type="text" /> <input type="radio" name="name" checked="checked" />
CSS related knowledge
introduce
CSS(Cascading Style Sheets) is often called CSS style sheets or cascading style sheets (cascading style sheets).
The greatest contribution of CSS: it separates HTML from style, realizes HTML to focus on structural presentation, and gives the style to CSS
effect
- It is mainly used to set the text content (font, size, alignment, etc.) \ picture shape (width, height, border style, margin, etc.) in HTML pages, as well as the layout and appearance display style of the layout.
- Based on HTML, CSS provides rich functions, such as font, style, background control and overall layout, and can set different styles for different browsers.
Introduction of CSS
1. Inline (inline style)
Set the style of the element through the style attribute of the label
- style is actually the attribute of the tag
- Between style attribute and value: wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
- Multiple sets of attribute values are used directly; separate
- It can only control the current label and the word label nested in it, resulting in code redundancy.
- **Disadvantages: * * there is no separation of style and structure.
<Tag name style="Attribute 1:Attribute value 1; Attribute 2:Attribute value 2; Attribute 3:Attribute value 3;"> content </Tag name> For example: <div style="color: red; font-size: 12px;">Youth doesn't often exist. Hurry up and fall in love</div>
Inline style sheet (2)
Also known as embedded, CSS code is written in the head tag of HTML document and defined with style tag.
- The style tag is usually located in the head tag. Of course, in theory, it can be placed anywhere in the HTML document.
- type = "text/css" can be omitted in html5.
- Only the current page can be controlled
- **Disadvantages: * * structure and style are not completely separated
<head> <style type="text/CSS"> Selector (selected label) { Attribute 1: Attribute value 1; Attribute 2: Attribute value 2; Attribute 3: Attribute value 3; } </style> </head>
3. External style sheet (external chain)
Also known as chain in, it is to put all styles in one or more In the external style sheet file with css extension, link the external style sheet file to the HTML document through the link tag.
- rel: defines the relationship between the current document and the linked document. It needs to be specified as "stylesheet" here, indicating that the linked document is a style sheet file.
- href: defines the URL of the linked external style sheet file, which can be a relative path or an absolute path.
<link rel="stylesheet" href="index.css">
4. Summary
style sheet advantage shortcoming Usage Control range Inline style sheet Convenient writing and high weight Structure style mixing, cumbersome less Single label Internal style sheet Part of the structure is separated from the style Not completely separated from the style many Single page External style sheet Complete separation Need to introduce most Multiple pages 5. Code style
/*1.Compact format*/ h3 { color: deeppink;font-size: 20px;} // 2. One is expansion format (recommended) h3 { color: deeppink; font-size: 20px; } /* Team conventions - Code Case*/ /* Style selectors, attribute names, attribute values and keywords are all written in lowercase letters, and attribute strings are allowed to use case.*/ /* recommend */ h3{ color: pink; } /* Not recommended */ H3{ COLOR: PINK; }
CSS base selector
CSS change style template: selector {changed style}
selector effect shortcoming Usage usage tag chooser You can select all the same tags, such as p No differentiated choice More p { color: red;} Class selector One or more labels can be selected You can choose according to your needs Very many, often used to modify styles .nav { color: red; } id selector Only 1 label can be selected at a time It can only be used once Not recommended #nav {color: red;} Wildcard selector Select all labels There are too many choices, some of which are not needed Not recommended * {color: red;} CSS composite selector
Compound selector is composed of two or more basic selectors combined in different ways
Descendant selector (including selector)
- Used to select descendants of an element or group of elements
- The writing method is to write the outer label in the front and the inner label in the back, separated by * * space * * in the middle. First write father and grandfather, and then write son and grandson.
- Future generations can choose this. In other words, it can select any tag included.
Parent child{attribute:Attribute value;attribute:Attribute value;} .class h3 {color:red;font-size:16px;}
- When tags are nested, inner tags become descendants of outer tags.
- Future generations can choose this. In other words, it can select any tag included.
Child Selector
- The child element selector can only select an element that is a child element (parent son) of an element.
- The way to write it is to write the parent label in front and the child label in the back, followed by a > in the middle
- The son here refers to his own son. Grandchildren and grandchildren are not included.
.class>h3 {color:red;font-size:14px;}
Intersection selector
- The first is the label selector and the second is the class selector. There can be no space between the two selectors, such as H3 special.
Intersection selector is and,Namely...also...The meaning of For example: p.one The selected is: the class name is .one Paragraph label for. /*Relatively few are used and are not recommended.*/
Union selector
If some selectors define the same style, you can use the union selector to make the code more concise. Union selectors (CSS selector groups) are formed by connecting selectors. They are usually used for collective declaration.
- Any form of selector (including label selector, class selector, id selector, etc.) can be used as part of the union selector.
- Union selectors are usually used for collective declaration. They are separated by commas. All selectors will execute the following style. Commas can be understood as and.
such as .one, p , #test {color: #F00;} express .one and p and #test all three selectors execute in red. Usually used for collective statements.
Link pseudo class selector
Use to add special effects to some selectors. When writing, try not to reverse their order and follow the lvha (formula love hate) order. Otherwise, errors may be caused.
The link pseudo class uses the intersection selector
- a: Linkunreached links
- a:visited visited links
- a:hover mouse over link
- a:active selected link
selector effect features Usage Separation symbol and usage Descendant Selectors Used to select descendants of elements Is to choose all future generations More Symbols are spaces nav a Progeny selector Select the nearest element Only choose your own son less The symbol is > nav>p Intersection selector Select the part where the two labels intersect Both and less No sign p.one Union selector Select some selectors of the same style Can be used for collective statements More The symbol is a comma nav, .header Link pseudo class selector Change status for link Add special effects to some selectors More Remember a{} and a:hover's actual development CSS font properties
Font font
attribute Attribute value express Attention font-size pixel Font size The unit we usually use is px pixel. We must keep up with the unit font-family Chinese / English / Unicode code typeface In the actual work, write the font according to the team agreement font-weight normal/bold/100-900 Font weight Remember that bold is 700 or bold and no bold is normal or 400. Remember that numbers do not follow units font-style normal/italic Font style Remember that tilting is italic and not tilting is normal, which is the most commonly used normal in our work font compound attribute writing method:
selector { font: font-style font-weight font-size/line-height font-family;}
- Note: when using the font attribute, it must be written in the order in the above syntax format, and the order cannot be changed. Each attribute is separated by spaces (the attributes that do not need to be set can be omitted (take the default value), but the font size and font family attributes must be retained, otherwise the font attribute will not work.)
CSS text properties (appearance)
attribute Attribute value express Attention color Color name / hex #FF0000-#FF6600/ RGB format: rgb(255,0,0) or rgb(100%, 0%, 0%) colour We usually use hexadecimal, for example, and it is abbreviated #fff line-height Pixel px, relative value em and percentage% Row height Controls the distance between rows. Row height = upper distance + content height + lower distance text-align left/right/center horizontal alignment You can set the horizontal alignment of text text-indent Pixel px, relative value em and percentage% text-indent Usually, we use the distance text indent: 2em to indent the first line of a paragraph by 2 words; text-decoration none/underline/overline/line-through Text modification Remember to add underline and UN underline none CSS background
attribute effect value background-color background color Predefined color values / hex / RGB codes background-image Background picture URL (picture path) background-repeat Tiled repeat/no-repeat/repeat-x/repeat-y background-position Background position length/position are x and Y coordinates respectively. Remember that if there is an accurate numerical unit, it must be written in the way of X before y. The Wizard will often use it background-attachment Fixed or scrolling background scroll/fixed Compound writing Simpler Background color background picture address background tile background scroll background position; They have no order Background transparency Make the box translucent background: rgba(0,0,0,0.3); Must be followed by 4 values Display mode (display)
The label display mode is how labels are displayed. HTML tags are generally divided into block tags and inline tags, which are also called block elements and inline elements.
Label display mode conversion display
- Block to line: display:inline;
- Intra row block transfer: display:block;
- Block and inline element are converted to inline block: display: inline block;
Block level element
Common block elements are
<h1>~<h6>,<p>,<div>,<ul>,<ol>,<li>
Etc., where
Tags are the most typical block elements.-
Characteristics of block level elements
-
- Exclusive row
- Height, width, outer margin and inner margin can be controlled.
- The width defaults to 100% of the container (parent width)
- Is a container and box that can release internal or block level elements
- Note: only text can form paragraphs, so block level elements cannot be placed in the p tag, especially p cannot put div. Similarly, there are h1~h6 and dt, which are text block level labels, and no other block level elements can be placed in them.
Inline level
Some places are also called inline elements. Common inline elements are:
<a>,<strong>,<b>,<em>,<i>,<del>,<s>,<ins>,<u>,<span>,
-
Characteristics of inline elements
-
- Elements in adjacent rows are on one row, and multiple elements can be displayed in one row.
- The direct setting of height and width is invalid.
- The default height is the width of its own content.
- Inline elements can only hold text or other inline elements.
be careful
- No more links can be placed in the link
- In special cases, block level elements can be placed in a, but it is safest to convert block level mode to a.
Inline block element
There are several special tags in inline elements
<img>,<input >,<td>
You can set width, height and alignment attributes on them. Some data may call them inline block elements.
-
Characteristics of inline block elements
-
- And adjacent inline elements (inline blocks) on the same line, but there is a risk of whitespace between them. A row can display more than one
- The default width is the width of its own content.
- Height, row height, outer margin and inner margin can be controlled.
summary
Element pattern Element arrangement Set style Default width contain Block level element Only one block level element can be placed in a row You can set the width and height 100% of container The container level can contain any label Inline element A row can hold multiple inline elements The width and height cannot be set directly The width of its own content To hold text or other inline elements Inline block element Place multiple inline block elements in a row You can set the width and height The width of its own content Box model
Three key points of css learning: css box model, floating and positioning
The essence of web layout
- First, use CSS to set the size of the box, and then place the position of the box.
- Finally, put the web page elements, such as text, pictures and so on, into the box.
Box model
- The box model regards the layout elements in HTML pages as a rectangular box, that is, a container for content.
- The box model consists of the content, border, padding, and margin of the element.
- The text, pictures and other elements in the box are the content area
- The thickness of the box is called the frame of the box
- The distance between the box content and the border is the inner margin
- The distance between boxes is the outer margin
W3c standard box model
The scope of the standard w3c box model includes margin, border, padding and content
When set to box sizing: content box; When, the standard mode will be used for analytical calculation, which is also the default mode;
Inner box size calculation(Actual size of element)
- Width: Element Height = content height + padding + border (Height is content Height)
- Height: Element Width = content width + padding + border (Width is content Width)
- Actual size of box: width and height of content + inner margin + border
IE box model
The content part of the IE box model contains border and padding
When it is set to box sizing: border box, the weird mode will be used for analytical calculation;
Box border
attribute effect border-width Defines the border thickness in px border-style The style of the border border-color Border color Border style:
- none: if there is no border, the width of all borders is ignored (default)
- Solid: the border is a single solid line (the most commonly used)
- Dashed: the border is dashed
- Dotted: the border is dotted
Comprehensive border settings border : border-width || border-style || border-color border: 1px solid red; No sequence requirements
Summary of box border writing:
In many cases, we do not need to specify four borders. We can specify four borders separately.
border-top bottom border-left border-right Border top style: style; Border bottom style: style; Border left style: style; Border right style: style; Border top width: width; Border - bottom width: width; Border left width: width; Border right width: width; Border top color: color; Border - bottom color: color; Border left color: color; Border right color: color; Border top: width style color; Border bottom: width style color; Border left: width style color; Border right: width style color; Thin border of table:
-
Set the distance between cells to 0 through cellspacing="0" in the table,
-
However, the border between the two cells overlaps, making the border thicker
-
Through css attribute: table {border collapse: collapse;}
-
- The word collapse means merge, border collapse: collapse; Indicates that adjacent borders are merged together.
<style> table { width: 500px; height: 300px; border: 1px solid red; } td { border: 1px solid red; text-align: center; } table, td { border-collapse: collapse; /*Merge adjacent borders*/ } </style>
Inner margin (padding)
The padding property is used to set the inside margin. Refers to the distance between the border and the content.
set up
attribute effect padding-left Left inner margin padding-right Right inner margin padding-top Upper inner margin padding-bottom Lower inner margin padding abbreviation
Number of values Express meaning 1 value padding: up, down, left and right inner margins; 2 values padding: upper and lower inner margins, left and right inner margins; 3 values padding: upper inner margin, left and right inner margin, lower inner margin; 4 values padding: upper inner margin right inner margin lower inner margin left inner margin; When we assign the padding value to the box, two things happen:
- There is a distance between the content and the border, and an inner margin is added.
- The box will get bigger
**Solution: * * maintain the original size of the box by setting the width and height of the box and subtracting the corresponding inner margin.
**Padding does not affect the box size: if you do not specify a width for a box, if you specify padding for the box, the box will not be opened.
Outer margin
The margin property is used to set the margin. Margin is to control the distance between boxes
set up
attribute effect margin-left Left outer margin margin-right Right outer margin margin-top Upper outer margin margin-bottom Bottom outer margin The abbreviation of margin value (compound writing) means exactly the same as padding.
Block level box horizontally centered
- The box must have a width specified
- Then set the left and right outer margins to auto
This method is commonly used for web page layout in practical work. The example code is as follows:
.header { width: 960px; margin: 0 auto;}
The following three common ways of writing can be used
- margin-left: auto; margin-right: auto;
- margin: auto;
- margin: 0 auto;
The difference between text centered and box centered
- The horizontal center of the text in the box is text align: Center; You can also center inline elements and inline blocks
- The block level box is horizontally centered, and the left and right margin is changed to auto
Difference between insert picture and background picture
- We use the most to insert pictures, such as product display. The mobile position can only rely on the box model padding margin
- Background pictures are generally used for small icon background or large background pictures and background pictures. The position can only be moved through background position
Clears the default inside and outside margins of elements
- In order to take into account the compatibility of inline elements, try to set only the left and right inner and outer margins, not the upper and lower inner and outer margins.
* { padding:0; /* Clear inner margin */ margin:0; /* Clear outer margin */ }
Outer margin merge
When using margin to define the * * vertical outer margin * * of block elements, outer margins may be merged.
Merging of vertical outer margins of adjacent block elements
- When the upper and lower adjacent block elements meet, if the upper element has a lower outer margin margin margin margin bottom
- If the following elements have an upper and outer margin margin margin top, the vertical spacing between them is not the sum of margin bottom and margin top
- **"Take the larger of the two values" * * this phenomenon is called the merging of vertical outer margins of adjacent block elements (also known as outer margin collapse).
Solution: try to add margin value to only one box.
Merge (collapse) of vertical outer margins of nested block elements
- For two nested block elements, if the parent element has no upper and inner margins and borders
- The upper and outer margins of the parent element are merged with the upper and outer margins of the child element
- The combined outer margin is the greater of the two
"Solution:"
- You can define an upper border for the parent element.
- You can define the upper and inner margins for the parent element
- You can add overflow: hidden for the parent element.
There are other methods, such as floating, fixed and absolutely positioned boxes. We will summarize later...
Box model layout stability
Use width first, then padding and then margin
width > padding > margin
reason:
- Margin will have outer margin merging, and ie6 the following margin doubling bug (annoying), so it is used finally.
- padding will affect the size of the box, which needs to be added and subtracted (troublesome) and then used.
- Width is no problem (HI PI) we often use the width residual method and the height residual method.
CSS3 NEW
Rounded border: border-radius:length; border-top-left-radius Defines the radian of the upper left corner border-top-right-radius Defines the radian of the upper right corner border-bottom-right-radius Defines the radian of the lower right corner border-bottom-left-radius Defines the radian of the lower left corner
- Each of these values can be in the form of a number or a percentage.
- Tip: turn a square into a circle
border-radius: 50%;
If you want to specify each of the four corners, you can use the following rules 👇👇:
border-radius: Upper left corner upper right corner lower right corner lower left corner;
- Four values: the first value is the upper left corner, the second value is the upper right corner, the third value is the lower right corner, and the fourth value is the lower left corner.
- Three values: the first value is the upper left corner, the second value is the upper right corner and lower left corner, and the third value is the lower right corner
- Two values: the first value is the upper left corner and lower right corner, and the second value is the upper right corner and lower left corner
- One value: the four fillet values are the same
Box shadow(box-shadow): box-shadow: offset-x offset-y [blur [spread]] [color] [inset]
value describe offset-x The horizontal offset of the shadow. Positive numbers are offset to the right and negative numbers are offset to the left. offset-y The vertical offset of the shadow. Positive numbers are offset downward and negative numbers are offset upward. blur Optional. Shadow blur distance cannot be negative. spread Optional. Shadow size color Optional. The color of the shadow inset Optional. Indicates that an inner shadow is added, and the default is outer shadow div { width: 200px; height: 200px; border: 10px solid red; /* box-shadow: 5px 5px 3px 4px rgba(0, 0, 0, .4); */ /* box-shadow:Horizontal position vertical position blur distance shadow size (shadow size) shadow color inner / outer shadow; */ box-shadow: 0 15px 30px rgba(0, 0, 0, .4); }
float
float
Three mechanisms of CSS layout
The core of web layout is to use CSS to place boxes.
type
CSS provides three mechanisms to set the placement position of boxes: normal flow (standard flow), floating and positioning, among which:
Normal flow (standard flow)
-
Block level elements will occupy one row and be arranged from top to bottom;
-
- Common elements: div, hr, p, h1~h6, ul, ol, dl, form, table
-
The elements in the line will be arranged in order from left to right. If they touch the edge of the parent element, they will wrap automatically;
-
- Common elements: span, a, i, em, etc
float
- Let the box float from the ordinary flow, which is mainly used to display multiple block level boxes in a row.
location
- Set the box at a certain location in the browser - CSS can't do without positioning, especially the js special effects behind it.
What is a floating element? Floating means that an element with a floating attribute set will
- Out of control of standard ordinary flow, out of position, out of standard
- Move to the specified location.
effect
- Making multiple boxes (div) arranged horizontally in a row makes floating an important means of layout.
- It can realize the left-right alignment of the box and so on.
- Floating was first used to control the picture and realize the effect of text surrounding the picture.
- The float attribute changes the display attribute of the element, and any element can float. A floating element generates a block level box, regardless of what element it is. The resulting block level box is very similar to the in-line block we saw earlier.
Grammar (emphasis)
selector { float: Attribute value; }
Attribute value describe none Element does not float (default) left The element floats to the left right The element floats to the right Floating will only affect the current or subsequent standard flow box, and will not affect the previous standard flow.
**Suggestion: * * if there are multiple sub boxes in a box, if one box floats, other brothers should also float. Prevent problemsFloat summary
characteristic explain float The box with floating * * "floating" * * floats on top of other standard flow boxes. leak The floating box * * "does not occupy a position", and its original position "leaks to the standard flow box" * *. special Special note: floating elements will change the display attribute, which is similar to converting to inline blocks, but there is no gap between elements Clear float
In many cases, it is inconvenient to give the height of the parent box, but the floating of the child box does not occupy a position. Finally, the height of the parent box is 0, which affects the following standard flow box.
Summary:
- Since the floating element no longer occupies the position of the original file stream, it will affect the layout of subsequent elements
- To be precise, it is not to clear the float, but the impact caused by clearing the float
Clear floating essence clear floating is mainly used to solve the problem that the internal height of parent elements is 0 due to child floating. After floating is cleared, the parent will automatically detect the height according to the floating sub box. If the parent has a height, it will not affect the following standard flow
Method of clearing floating
selector { clear: Attribute value; } clear eliminate
Attribute value describe left Floating elements on the left are not allowed (clear the influence of floating on the left) right Floating elements on the right are not allowed (clear the influence of floating on the right) both At the same time, remove the influence of left and right floating In practical work, almost only clear: both
1). Additional labeling method (partition method)
The W3C recommends adding an empty tag at the end of a floating element, such as
, or other labels br, etc.- Advantages: easy to understand and write
- Disadvantages: add many meaningless tags and poor structure.
2). Parent add overflow attribute method
You can add to a parent: overflow by hidden| auto| scroll Can be achieved.
- Advantages: simple code
- Disadvantages: when the content increases, it is easy to cause no automatic line feed, resulting in the content being hidden and the elements to be overflowed cannot be displayed.
3). Use after pseudo elements to clear floating: the after method is an upgraded version of the additional labeling method for empty elements. The advantage is that there is no need to label separately
.clearfix:after { content: ""; display: block; height: 0; clear: both; visibility: hidden; } /* IE6,7 proper */ .clearfix { *zoom: 1; }
- Advantages: it conforms to the closed floating idea, and the semantic structure is correct
- Disadvantages: since IE6-7 does not support: after, use zoom:1 to trigger hasLayout.
4). Use double pseudo elements to clear floats
.clearfix:before, .clearfix:after { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; }
- Advantages: more concise code
- Disadvantages: since IE6-7 does not support: after, use zoom:1 to trigger hasLayout.
Clear floating summary
When to use clear float?
- The parent has no height
- The sub box floats
- The floating effect should be cleared below.
Clear floating mode advantage shortcoming Additional labeling method (partition method) Easy to understand and write Add a lot of meaningless tags, and the structure is poor. Parent overflow:hidden; Simple writing Overflow hiding Parent after pseudo element Correct semantic structure Because IE6-7 does not support: after, there is a compatibility problem Parent double pseudo element Correct semantic structure Because IE6-7 does not support: after, there is a compatibility problem Knowledge of Java Script
introduce
origin
Brendan EICH, originally named LiveScript, later renamed JavaScript in cooperation with Sun.
JavaScript is a script language running on the client side. It does not need to be compiled and is interpreted and executed line by line by js interpreter (js engine). Node.js can also be used for server-side programming.
JavaScript composition
ECMAScript(JavaScript syntax), DOM (document object model), BOM (browser object model)
Role (common scenarios)
- Form dynamic verification (password strength detection)
- Web effects
- Server development (Node.js)
- Desktop program (Electron), App(Cordova), control hardware - Internet of things (Ruff), game development (cocos2d JS)
JavaScript writing position
JS has three writing positions: inline, inline and external, which are similar to CSS.
1. Inline
<input type="button" value="Let me try" onclick="alert('Hello World')" />
2. Embedded
<script> alert('Hello World~!'); </script>
3. External
//Reference external js file <script src = "my.js"></script>
notes
Single-Line Comments
// I am a single line comment (Shortcut ctrl + /)
multiline comment
/* Get user age and name And displayed through the prompt box Click management - Keyboard Shortcuts - switch block notes in the lower left corner of vscode (The default shortcut alt + shift + a) is changed to (ctrl + shift + /) */
variable
Declare variable
var is a JS keyword used to declare variables (the meaning of variable). num is the variable name defined by us. You can access the allocated space in memory through the variable name.
var Variable name; var num; // Declare a variable named num
Variable assignment
num = 10;//Assign a value of 10 to the num variable
Initialization of variables
Declaring and assigning a variable is called variable initialization.
var num = 10;//Declare the variable and assign a value of 10
Variable syntax extension
// 1. After a variable is re assigned, its original value will be overwritten, and the variable value shall be subject to the last assigned value. var num = 10; num = 11; // 2. Declare multiple variables at the same time (only one var needs to be written, and multiple variable names are separated by English commas) var num = 10, age = 15, name = 'fan'; // 3. Multiple variable assignments such as concatenation cannot be used during declaration var a = b= c = 10; // If the last two are not declared, an error will be reported
Keywords and reserved words
Identifier: refers to the name obtained by the developer for variables, attributes, functions and parameters. Identifiers cannot be keywords or reserved words.
Keyword: refers to the words already used by JS itself. They can no longer be used as variable names and method names
Including: break, case, catch, continue, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with, etc.
Reserved words: actually, they are reserved "Keywords", which means that although they are not keywords now, they may become keywords in the future. Similarly, they cannot be used as variable names or method names.
boolean, byte, char, class, const, debugger, double, enum, export, extends, decimal, float, goto, implements, import, int, interface, long, automatic, package, private, protected, public, short, static, super, synchronized, throws, transient, volatile, etc.
Note: if a reserved word is used as a variable name or function name, it is likely that no error message will be received unless the reserved word is implemented in a future browser. When the browser implements it, the word will be regarded as a keyword, so a keyword error will appear.
data type
There are two types: simple data types (Number,String,Boolean,Undefined,Null) and complex data types (objects).
-
Simple type (basic data type, value type): during storage, the value itself is stored in the variable, including string, number, boolean, undefined and null
-
Complex data type (reference type): when storing, only the address (Reference) is stored in the variable, and the objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc;
Simple data type explain Default value Number Numeric type, including integer and floating-point values 0 String String type "" Boolean Boolean Boolean false Undefined var a; The variable a is declared but not assigned. In this case, a = undefined undefined Null var a = null; Declared that variable a is null null Number numeric
"Numeric base"
// 1. Add 0 before octal and 0x before hexadecimal in JS var num1 = 07; // Corresponding to decimal 7 // 2. Hexadecimal digit sequence range: 0 ~ 9 and A~F var num = 0xA;
Numeric ranges have maximum and minimum values
- Maximum value: number MAX_ Value: 1.7976931348623157e+308
- Minimum value: number MIN_ Value, value: 5e-32
- Special values: Infinity infinity, - Infinity infinitesimal, NaN represents a non number
- isNaN(): used to determine whether a variable is of non numeric type. The non numeric type is true and the numeric type is false.
String string type
// 1. The string type can be any text in quotation marks. The syntax is single quotation marks and double quotation marks var msg = 'My name is'; var name = "fan";
**"1. String escape characters" * * all start with \, as follows: 👇👇
Escape character explain \n Newline, n means newline \ Inclined rod\ \ ' Single quotation mark‘ \ " Double quotation mark“ \t tab indent \b b means blank "2. String length"
A string is composed of several characters. The number of these characters is the length of the string.// 1. The string type can be any text in quotation marks. The syntax is single quotation marks and double quotation marks var msg = 'I'm a handsome rice boss'; console.log(msg.length); // Display 8
"3. String splicing"
Multiple strings can be spliced with + in the form of string + any type = new string after splicing.
Before splicing, any type added to the string will be converted into a string, and then spliced into a new string//1.1 string "addition" alert('hello' + ' ' + 'world'); // hello world //1.2 numeric string "addition" alert('100' + '100'); // 100100 //1.3 numeric string + numeric alert('11' + 12); // Formula 1112 +: numerical values are added and characters are connected // 1.4 string splicing reinforcement var age = 18; alert("Rice boss this year" + age +"Years old");
Boolean
Boolean types have two values: true and false, where true represents true (true) and false represents false (false).
When Boolean and numeric types are added, the value of true is 1 and the value of false is 0.console.log(true + 1) // 2 console.log(false + 1) // 1
Undefined and Null
If a variable is declared without assignment, it will have a default value of undefined (if connected or added, pay attention to the result)
var variable; console.log(variable); // undefined console.log("Hello" + variable); // Hello, undefined console.log(11 + variable); // NaN console.log(true + variable);// NaN
A variable is declared and assigned null, and the stored value is null
var var2 = null; console.log(var2); // null console.log("Hello" + var2); // Hello, null console.log(11 + var2); // 11 console.log(true + var2);// 1
Get variable type and conversion (key)
- The data type of the detection variable is typeof
var num = 10; console.log(typeof num)//The result is number
-
Literal quantity: it is the representation of a fixed value in the source code, that is, how to express this value. The type of data can be determined by the format characteristics of the data
-
- Number literal: 8,9,10
- String literal: 'rice boss',' front-end development '
- Literal: true, Boolean: false
Data type conversion
- Convert to string
mode explain case toString() Convert to string var num=1; alert(num.toString()) String() Force conversion var num=1; alert(String(num)) Plus concatenated string And string splicing results are strings var num=1; alert(num + 'I am a string') - Convert to numeric
mode explain case parseInt(String) function Convert string type to integer type parseInt('11') parseFloat(String) function Convert string type to floating point type parseFloat('11.2') Number() cast function Cast string type to numeric type Number('12') js implicit conversion (- * /) Implicit conversion to numerical type by arithmetic operation '12' - 0 - Convert to Boolean
Values representing null and negative will be converted to false, such as' ', 0, NaN, null, undefined, and other values will be converted to true
mode explain case Boolean() Convert other types to Booleans Boolean('true') function
It encapsulates a code block that can be repeatedly called and executed. A large number of codes can be reused through functions. A function is a data type.
Use of functions
Declarative function
1. adopt function Keyword definition function -- Named function function Function name() { //Function body code } // 1.1 function is the keyword to declare the function, which must be lowercase // 1.2 name the function as a verb. Example: getSum 2. Defining functions through function expressions ---Anonymous function var fn = function() {}; // 2.1 fn is a variable name, not a function name // 2.2 fn is a variable, but the variable stores a function // 2.3 functions created by function expressions can be created by variable names (); To call // 2.4 function expressions can also define formal parameters and call incoming arguments. The second way to use anonymous functions--Anonymous function self call (function(){ alert(123); })();
Call function
Function name();// After the function declaration, the function code is executed.
Encapsulation of functions
- Function encapsulation is to encapsulate one or more functions through functions, and only provide a simple function interface.
/* For example, use the encapsulation function to calculate the 1-100 cumulative sum */ function getSum() { var sumNum = 0; // Prepare a variable and save the cumulative sum for (var i = 1; i <= 100; i++) { sumNum += i; // Add each value to the variable } alert(sumNum); } // Call function getSum();
Parameters of function
- Formal parameters: parameters passed during function definition (actual parameter values are passed to formal parameters, and variables are not declared)
- Argument: parameter passed during function call
//Function declaration with arguments function Function name(Formal parameter 1,Formal parameter 2,Formal parameter 3...) { //Function body } // Function call with arguments Function name(Argument 1,Argument 2,Argument 3...);
- When the number of function parameters and arguments does not match
Number of parameters explain The number of arguments is equal to the number of formal parameters Output correct results The number of arguments is more than the number of formal parameters Only get the number of formal parameters The number of arguments is less than the formal parameter Multiple formal parameters are defined as undefined and the result is NaN function getSum(a, b, c) { return a + b + c; } // The default value of the formal parameter in js is undefined. // Call function var n = getSum(1, 2);// n = NaN var n = getSum(1, 2, 3, 4); //1 + 2 +3 = 6
Return value of function
Return value: the data represented by the function call as a whole; After the function is executed, you can return the specified data through the return statement.
// Declarative function function Function name() { ... return Value to return; // 1. When the function encounters return, it will stop execution and return the specified value // 1. If the function does not return, the returned value is undefined } // Call function Function name(); //At this point, you can call the function to get the return value in the function body break,continue,return Differences between
- break: end the current loop body (e.g. for, while)
- Continue: jump out of this cycle and continue to execute the next cycle
- Return: it can not only exit the loop (in the function body), but also return the value in the return statement. At the same time, it can also end the code in the current function body
//Avoid stepping on pits. return can only end the code in the function body function breakDown() { for (var i = 0; i < 10; i++) { if (i == 5) { return 1; } console.log(i); } } breakDown(); //Avoid stepping on the pit 2. If the function has a return, it returns the value after the return; // return d,a,b; Returns the value of B //If the function does not have a return statement, it returns undefined
Use of arguments
When you are not sure how many parameters are passed, you can use arguments to get them. In JS, arguments is actually a built-in object of the current function. All functions have a built-in arguments object in which all arguments passed are stored. Arguments is displayed as a pseudo array, so it can be traversed.-
Pseudo arrays have the following characteristics:
-
- With length attribute
- Store data by index
- push, pop and other methods without array
function fn() { //Arguments stores all passed arguments console.log(arguments);// [1,2,3...] console.log(arguments[1]); // 2 console.log(arguments.length); // 3 //We can traverse the argument as an array } fn(1, 2, 3); // Using pseudo array to find the maximum value function getMax() { var max = arguments[0]; for (var i = 1; i < arguments.length; i++) { if (arguments[i] > arguments[0]) { max = arguments[i]; } } return max; } var result = getMax(1,3,77,5,85) colsole.log(result);
Scope
**Scope * * the name used in a piece of program code is not always valid and reliable, and the scope of the availability code that limits the name is the scope of the name.
- The use of scope improves the locality of program logic, enhances the reliability of program, and reduces name conflict.
- Before ES6, there were two scopes: global scope and local scope (function scope)
**"Global scope" * * applies to all code execution environments (within the entire script tag) or an independent js file.
**Local scope * * acts on the code environment inside the function, which is the local scope. Because it is related to functions, it is also called function scope.
"JS has no block level scope"
- Block scope is included by {}
- In other programming languages, in the if statement, the variables created by the loop statement can only be used in this if statement and this loop statement, as shown below
if(true){ int num = 123; System.out.print(num); //123 } System.out.print(num);//report errors
- The above java code will report an error because {} in the code is a scope, and the declared variable num cannot be used outside {}, while JavaScript code will not report an error
- No block level scope in Js (before ES6)
if(true){ var num = 123; console.log(num); // 123 } console.log(num);// 123
Scope of variable
In JavaScript, variables can be divided into global variables and local variables according to different scopes:
global variable
Variables declared under the global scope (variables defined outside the function)
- Global variables can be used anywhere in the code
- The variables declared by var under the global scope are global variables
- In special cases, variables that are not declared with var in a function are also global variables (not recommended).
local variable
Variables declared under local scope (variables defined inside a function)
- Local variables can only be used inside functions
- The variables declared by var inside the function are local variables
- The formal parameters of a function are actually local variables
The difference between global variables and local variables
- **Global variable: * * can be used anywhere. It will be destroyed only when the browser is closed, so it takes up more memory
- **Local variables: * * are intended for internal use in functions. They are initialized only when the code block they are in is executed; After the contemporary code block runs, it will be destroyed, so it saves more memory space.
Pre analysis
**Concept: * * JavaScript code is executed by a JavaScript parser in the browser. The JavaScript parser runs JavaScript code in two steps: pre parsing and code execution.
- **Pre parsing: * * under the current scope, the browser will declare or define variables with var and function declarations in memory by default before JS code execution.
- Code execution: execute JS statements from top to bottom
Pre parsing completes the declaration of variables and functions before code execution. Pre parsing is also called variable and function promotion. Examples are as follows:
Variable pre parsing (variable promotion)
The declaration of the variable will be promoted to the top of the current scope, and the assignment of the variable will not be promoted.
console.log(num); // What's the result? var num = 10; // ? amount to var num; console.log(num);// The result is undefined num = 10; result: undefined be careful: Variable promotion only promotes declarations, not assignments.
Function pre parsing (function promotion)
The declaration of the function will be promoted to the top of the current scope, but the function will not be called.
fn(); function fn() { console.log('Print'); } result: Console print string --- "Print" be careful: The function declaration represents the whole function, so after the function is promoted, the function name represents the whole function, but the function is not called!
Function expression declaration problem
When a function is created by a function expression, the variable promotion will be executed. At this time, the variable name of the receiving function cannot be called correctly fn(); var fn = function(){ console.log("I don't think so"); } result:Error reporting prompt "fn is not a function" explain: Before the code is executed, the variable declaration will be promoted, fn Value after promotion yes undefined;and fn Call is in fn Before being assigned to the function body, here fn The value of is undefined,So it can't be called. Pre analysis case 1 var num = 10; fun(); function fun(){ console.log(num); var num = 20; } It is equivalent to performing the following operations and printing the results undefined var num; function fun(){ var num; console.log(num); num = 20; } num = 10; fun(); Pre analysis case 2 var a = 18; f1(); function f1(){ var b = 9; console.log(a); console.log(b); var a = '123'; } It is equivalent to performing the following operations, and the result is undefined 9 var a; function f1(){ var b; var a; b = 9; console.log(a); console.log(b); a = '123'; } a = 18; f1(); Pre analysis case 3 f1(); console.log(c); console.log(b); console.log(a); function f1() { var a = b = c = 9; console.log(a); console.log(b); console.log(c); } It is equivalent to performing the following operations, and the result is 9 "report errors--a is not defined" function f1() { var a; a = b = c = 9; //Equivalent to var a = 9; b=9; c=9; b and C are assigned directly, without var declaration, when viewed as global variables. // Difference: collective declaration var a = 9,b = 9, c = 9; console.log(a); console.log(b); console.log(c); } f1(); console.log(c); console.log(b); console.log(a);
object
Concept of object
Object: in JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.
-
Objects are composed of properties and methods
-
- Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)
- Method: the behavior of things is often expressed in the object (common verb)
"Why do you need objects?"
- When saving a value, you can use variables. When saving multiple values (a group of values), you can use arrays. What if you save the complete information of one?
- In order to better store a set of data, object application is born; The attribute name is set for each item of data in the object, which can access the data more semantically, with clear data structure and obvious meaning, which is convenient for developers to use.
var obj = { "name":"fan", "sex":"male", "age":18, "height":155 }
Three ways to create objects
1. Create objects with literal values create objects with literal values:
- The curly braces {} contain the attributes and methods of expressing this specific thing (object); {} is represented in the form of key value pairs
-Key: equivalent to attribute name
-Value: equivalent to attribute value and can be any type of value (numeric type, string type, boolean type, function type, etc.)
// star is the object created var star = { name : 'pink', age : 18, sex : 'male', sayHi : function() { alert('Hello, everyone'); } };
-
Use of objects
-
- Attribute of object: the key in the "key value pair" in which specific data is stored in the object is called the attribute of the object, that is, the item in which specific data is stored in the object.
- Object method: the "key" in the "key value pair" of the stored function in the object is called the object method, that is, the item of the stored function in the object.
- Accessing the properties of an object: calling the properties in the object Attribute name; Another way to call attributes in an object: Object ['attribute name'). Note that the attributes in square brackets must be quoted.
- Method of calling object: object Method name ();
- Summary of variables, attributes, functions and methods:
â‘ Variable: independent declaration and assignment, independent existence
â‘¡ Attribute: variables in an object are called attributes and do not need to be declared. They are used to describe the characteristics of the object.
â‘¢ Method: a method is a part of an object, a function is not a part of an object, and a function is a container that encapsulates operations separately. The function in the object is called a method. The method does not need to be declared. It can be called by using "object. Method name ()". The method is used to describe the behavior and function of the object.
â‘£ Function: it exists separately and can be called by "function name ()".
console.log(star.name) // Call name property console.log(star['name']) // Call name property star.sayHi();
2. Create an object using new Object
- Create an empty object
Through the built-in constructor Object The object is created and the andy The variable has saved the created empty object var andy = new Object();
- Add properties and methods to an empty object
Add attributes and methods to objects by manipulating them andy.name = 'pink'; andy.age = 18; // andy.age = 19 modify object properties andy.sex = 'Male;// andy.phoneNum = 110 add attribute andy.sayHi = function() { alert('hello everyone'); } obj.sayHi();Call the method of the object //The second is obj['sayHi '] (); // The first letter of Object() is capitalized; //new Object() requires the new keyword. The format used is: object Attribute = value
3. Create objects using constructors
Constructor is a special function, which is mainly used to initialize an object, that is, to assign initial values to object member variables. It is always used together with the new operator. We can extract some public properties and methods from the object and encapsulate them into this function.
- Encapsulation format of constructor:
function Constructor name(Parameter 1, parameter 2, parameter 3...) { this.Property name 1 = Parameter 1; this.Property name 2 = Parameter 2; this.Property name 3 = Parameter 3; this.Method name = Function body; }
- Call format of constructor
var obj = new Constructor name(Argument 1, argument 2, argument 3); // In the above code, obj receives the object created by the constructor. matters needing attention: 1.Constructor convention initial capitalization 2.The properties and methods in the function need to be added in front this,Represents the properties and methods of the current object 3.Not required in constructor retrun Return results 4.But when we create objects, we must use new To call the constructor 1.Others: constructors such as Stars(),The common part of the object is extracted and encapsulated into the function Generally refers to a large class(class) 2.Create objects, such as new Stars();Especially one that uses new Keyword the process of creating an object We also call it object instantiation
-
Function of new keyword (interview question)
-
- 1. Create an empty object before the constructor code starts executing;
- 2. Modify the point of this and point this to the created empty object;
- 3. Execute the code in the constructor and add properties and methods to the new object
- 4. After the function is completed, return the created new object (so return is not required in the constructor)
// The factory function creates an object, which returns the created object to the function call function createPerson(name, age, job) { var person = new Object(); person.name = name; person.age = age; person.job = job; person.sayHi = function(){ console.log('Hello,everyBody'); } return person; } var p1 = createPerson('Zhang San', 22, 'actor');
Traversal object
The for... in statement is used to perform a circular operation on the attributes of an array or object.
The syntax is as follows: for (variable in Object name) { // Execute code here } The variable in the syntax is user-defined. It needs to comply with the naming convention. Usually, we will write this variable as k perhaps key. for (var k in obj) { console.log(k); // k here is the attribute name console.log(obj[k]); // obj[k] here is the attribute value }
Built in object
Built in objects: there are three types of objects in JavaScript: custom objects, built-in objects, and browser objects
The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS. JS API explains that built-in objects refer to some objects of JS language. These objects are used by developers and provide some common or most basic rather than necessary functions (properties and methods). The biggest advantage of built-in objects is to help us develop quickly."Check the document to learn how to use a built-in object. Just learn how to use its common members. We can learn by checking the document.
Math object
Math object: it is not a constructor. It has properties and methods of mathematical constants and functions. It is related to mathematics.
Property, method name function Math.PI PI Math.floor() Round down Math.ceil() Round up Math.round() The rounded version is rounded to the nearest. Note - 3.5. The result is - 3 Math.abs() absolute value Math.max()/Math.min() Find the maximum and minimum values Math.random() Gets a random value in the range [0,1] - Gets a random integer in the specified range function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
Date object
Date object is different from Math object. Date is a constructor, so you need to instantiate it before you can use its specific methods and properties. The date instance is used to process date and time
Instantiate a Date object with Date
-
- Get current time must be instantiated
- Gets the date object for the specified time
var now = new Date(); var future = new Date('2020/10/1') // Note: if no parameter is passed in when creating an instance, the date object obtained is the date object corresponding to the current time
-
Continued
-
- Methods and properties using Date instances
- Month obtained by getMonth() method + 1 = current month
//Parameters are usually written in numeric or string form '2019-10-1 8:8:8' var date1 = new Date(2019,10,1); //Date formatting // Format date: mm / DD / yy var date = new Date(); console.log(date.getFullYear()); //Returns the year 2020 of the current date console.log(date.getMonth() + 1); //The month returned in the month is 1 month smaller. Remember to add 1 month to the month console.log(date.getDate()); //What number is returned console.log(date.getDay); //Monday returns 1, Saturday returns 6, and Sunday returns 0 //We write a Sunday, September 6, 2020 var year = date.getFullYear(); var month = date.getMonth() + 1; var dates = date.getDate(); var day = date.getDay(); if (day == 0) { day = "Sunday"; } console.log("Today is" + year + "year" + month + "month" + dates + "day" + day); //Format date hour minute second var date = new Date(); console.log(date.getHours()); //Time console.log(date.getMinutes()); //branch console.log(date.getSeconds()); // second //Encapsulate a function to return the current time, minute and second format 08:08:08 function getTimer() { var time = new Date(); var h = time.getHours(); var h = h < 10 ? "0" + h : h; var m = time.getMinutes(); var m = m < 10 ? "0" + m : m; var s = time.getSeconds(); var s = s < 10 ? "0" + s : s; return h + ":" + h + ":" + s; } console.log(getTimer());
Gets the total number of milliseconds (timestamp) of the Date
Based on milliseconds since January 1, 1970 (world standard)
// Instantiate Date object var now = new Date(); // 1. Used to obtain the original value of the object console.log(now.valueOf()) console.log(now.getTime()) // 2. Simple writing can do this (the most commonly used) var now = + new Date(); // 3. The method provided in HTML5 has compatibility problems var now = Date.now(); Countdown case: 1. The input time minus the current time is the remaining time, that is, the countdown. 2.The timestamp is used to subtract the total milliseconds of the current time from the total milliseconds of the user input time, The result is the number of milliseconds remaining 3.Convert the total milliseconds of the remaining time into days, hours, minutes and seconds (Timestamp conversion time, minutes and seconds) The conversion formula is as follows: d = parseInt(Total seconds/60/60/24) // Calculation days h = parseInt(Total seconds/60/60%24) // Calculate hours m = parseInt(Total seconds/60%60); // Calculate minutes s = parseInt(Total seconds%60); // Calculate current seconds // Implementation of countdown case encapsulation function function countDown(time) { var nowTime = +new Date(); // Returns the total number of milliseconds of the current time var inputTime = +new Date(time); // Returns the total number of milliseconds of user input time var times = (inputTime - nowTime) / 1000; // times is the total number of seconds remaining var d = parseInt(times / 60 / 60 / 24); // day d = d < 10 ? "0" + d : d; var h = parseInt((times / 60 / 60) % 24); //Time h = h < 10 ? "0" + h : h; var m = parseInt((times / 60) % 60); // branch m = m < 10 ? "0" + m : m; var s = parseInt(times % 60); // Current seconds s = s < 10 ? "0" + s : s; return d + "day" + h + "Time" + m + "branch" + s + "second"; } console.log(countDown("2020-10-1 18:00:00")); var date = new Date(); console.log(date);
Array object
Two ways to create arrays
-
Literal method: var arr = [1, "test", true];
-
Instantiate array object new Array(): var arr = new Array();
-
- Note: in the above code, arr creates an empty Array. If you need to use the constructor Array to create a non empty Array, you can pass in parameters when creating the Array
- If only one parameter (number) is passed in, the parameter specifies the length of the array.
- If more than one parameter is passed in, the parameter is called an element of the array.
Detect whether it is an array
-
1. instanceof operator
instanceof can determine whether an object is an instance of a constructor
var arr = [1, 23]; var obj = {}; console.log(arr instanceof Array); // true console.log(obj instanceof Array); // false
-
2. Array.isArray()
Array.isArray() is used to determine whether an object is an Array.isArray() is a method provided in HTML5
var arr = [1, 23]; var obj = {}; console.log(Array.isArray(arr)); // true console.log(Array.isArray(obj)); // false
-
3. Pay attention to the usage of typeof
typeof is used to determine the type of variable
var arr = [1, 23]; console.log(typeof arr) // The object object arr is an instance of the constructor and is therefore an object data type
Methods for adding and deleting array elements
- There are methods to add and delete elements in the array. Some methods are shown in the table below 👇
var arr = [1, 2, 3]; console.log(arr.push(4, 5)); // 5 add elements to the end of the array arr.pop(); //Deletes the last value of the array and returns console.log(arr); // [1,2,3,4] // Adds an element to the beginning of an array and returns the length of the array console.log(arr.unshift(5, 6)); // 6 array becomes [5,6,1,2,3,4] console.log(arr.shift()); // 5 delete the element at the beginning of the array and return the value
Array sorting method
- There are methods to sort the array itself in the array. Some methods are shown in the table below
Method name explain Modify original array reverse() Invert the order of elements in the array without parameters This method will change the original array and return a new array sort() Sort the elements of the array This method will change the original array and return a new array -
Note: the sort method needs to pass in parameters (functions) to set ascending and descending sorting
-
- If "function (a, b) {return A-B;}" is passed in, In ascending order
- If "function (a, b) {return B-A;}" is passed in, In descending order
// Pit array sort (bubble sort) return a - b will be in ascending order // The writing method is fixed as follows: var arr1 = [13,4,77,1,7]; arr1.sort(function(a,b){ return a-b; }); console.log(arr1);
Array index method
- There are methods to obtain the index value of the specified element of the array. Some methods are shown in the table below
var arr = [1, 2, 3, 4, 5, 4, 1, 2]; // Find index of element 2 console.log(arr.indexOf(2)); // 1 // Find the last index of element 1 in the array console.log(arr.lastIndexOf(1)); // 6
Convert array to string
- There are methods to convert an array into a string in the array. Some methods are shown in the table below
- Note: if the join method does not pass in parameters, the elements will be spliced according to ","
var arr = [1, 2, 3, 4]; var arr2 = arr; var str = arr.toString(); // Convert array to string console.log(str); // 1,2,3,4 var str2 = arr2.join("|");//Converts an array to a string according to the characters you type console.log(str2);
Other methods
var arr = [1, 2, 3, 4]; var arr2 = [5, 6, 7, 8]; var arr3 = arr.concat(arr2); console.log(arr3); // [1,2,3,4,5,6,7,8] // slice(begin,end) is a left closed right open interval [1,3] // Intercept from index 1 to index 3 var arr4 = arr.slice(1, 3); console.log(arr4); // [2,3] var arr5 = arr2.splice(0, 3); console.log(arr5); // [5,6,7] console.log(arr2); // [8] Splice() affects the original array
String object
Basic package type
To facilitate the manipulation of basic data types, JavaScript also provides three special reference types: String, Number, and Boolean.
The basic wrapper type is to wrap a simple data type into a complex data type, so that the basic data type has properties and methods.// What's wrong with the following code? var str = 'andy'; console.log(str.length); // 4
In principle, basic data types have no attributes and methods, while objects have attributes and methods, but the above code can be executed because js will package basic data types as complex data types. The execution process is as follows:
// 1. Generate temporary variables and wrap simple types into complex data types var temp = new String('andy'); // 2. Assign a value to the character variable we declare str = temp; // 3. Destroy temporary variables temp = null;
Immutability of string
- It means that the value inside is immutable. Although it seems that the content can be changed, in fact, the address has changed and a new memory space has been opened up in the memory.
- When re assigning a value to a string variable, the previously saved string of the variable will not be modified. Re assigning a value to the string in memory will re open up space in memory. This feature is the immutability of the string.
- Due to the immutability of strings, there will be efficiency problems when * * a large number of spliced strings * *
Returns the position according to the character
- String through the basic wrapper type, you can call some methods to operate the string. The following is the method to return the position of the specified character:
var str = "anndy"; console.log(str.indexOf("d")); // 3 //Specifies that the character "d" is found starting at an index number of 4 console.log(str.indexOf("d", 4)); // -1 console.log(str.lastIndexOf("n")); // 2
Case: find the location and number of occurrences of all o in the string "abcoefoxyozopp"
- First find the location where the first o appears
- Then, as long as the result returned by indexOf is not - 1, continue to look back
- Because indexOf can only find the first one, the subsequent search uses the second parameter to add 1 to the current index to continue the search
var str = "oabcoefoxyozzopp"; var index = str.indexOf("o"); var num = 0; while (index !== -1) { console.log(index); num++; index = str.indexOf("o", index + 1); }
Returns characters based on position
- String through the basic wrapper type, you can call some methods to operate the string. The following is the character at the specified position returned according to the position:
// Return according to character position // 1. charAt(index) returns characters according to position var str = 'andy'; console.log(str.charAt(3)); // y // Traverse all characters for (var i = 0; i < str.length; i++) { console.log(str.charAt(i)); } // a n d y // 2. charCodeAt(index) //Returns the character ASCII value of the corresponding index number. Purpose: to determine which key the user pressed console.log(str.charCodeAt(0)); // 97 // 3. str[index] H5 NEW console.log(str[0]); // a
-
Case: judge the character that appears most frequently in a string 'abcoefoxyozopp', and count its times
-
- Core algorithm: use charAt() to traverse this string
- Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be + 1
- Traverse the object to get the maximum value and the character. Note: in the process of traversal, each character in the string is stored in the object as the attribute of the object, and the corresponding attribute value is the number of occurrences of the character
var str = "abcoefoxyozzopp"; var o = {}; for (var i = 0; i < str.length; i++) { var chars = str.charAt(i); // chars is each character of the string if (o[chars]) { // o[chars] gets the attribute value o[chars]++; } else { o[chars] = 1; } } console.log(o); // 2. Traversing objects var max = 0; var ch = ""; for (var k in o) { // k is the attribute name // o[k] gets the attribute value if (o[k] > max) { max = o[k]; ch = k; } } console.log(max); console.log("The maximum number of characters is" + ch);
String operation method
String through the basic wrapper type, you can call some methods to operate the string. The following are some operation methods:
// String operation method // 1. concat('string 1 ',' string 2 '...) var str = 'andy'; console.log(str.concat('red')); // andyred // 2. substr('intercept start position ',' intercept several characters'); var str1 = 'The spring breeze of reform is blowing all over the ground'; // The first 2 is the 2 of the index number, starting from the second 2, and the second 2 is the number of characters console.log(str1.substr(2, 2)); // spring breeze
-
replace() method
-
- The replace() method is used to replace some characters with others in the string. Its format is as follows:
character string.replace(The string to be replaced, the string to be replaced with)ï¼›
-
split() method
-
- The split() method is used to split strings, which can be split into arrays. After segmentation, a new array is returned.
- Its format is as follows:
character string.split("Split character") // 1. The replacement character replace('replaced character ',' replaced character ') will only replace the first character var str = "andyandy"; console.log(str.replace("a", "b")); // bndyandy // There is a string 'abcoefoxyozzopp' that requires all o's in it to be replaced with* var str1 = "abcoefoxyozzopp"; while (str1.indexOf("o") !== -1) { str1 = str1.replace("o", "*"); } console.log(str1); // abc*ef*xy*zz*pp // 2. Convert characters to array split('separator ') // We learned earlier that join converts an array into a string var str2 = "red, pink, blue"; console.log(str2.split(",")); //[red,pink,blue] var str3 = "red&pink&blue"; console.log(str3.split("&")); // [red,pink,blue]
nsole.log(str.charAt(3)); // y
//Traverse all characters
for (var i = 0; i < str.length; i++) {
console.log(str.charAt(i));
} // a n d y// 2. charCodeAt(index) //Returns the character ASCII value of the corresponding index number. Purpose: to determine which key the user pressed console.log(str.charCodeAt(0)); // 97 // 3. str[index] H5 NEW console.log(str[0]); // a
- Case: judge a string 'abcoefoxyozzopp' The character that appears the most times in and counts its times - 1. Core algorithm: Using charAt() Traverse this string 2. Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be 1 +1 3. Traverse the object to get the maximum value and the character. Note: in the process of traversal, each character in the string is stored in the object as the attribute of the object, and the corresponding attribute value is the number of occurrences of the character
var str = "abcoefoxyozzopp"; var o = {}; for (var i = 0; i < str.length; i++) { var chars = str.charAt(i); // chars is each character of the string if (o[chars]) { // o[chars] gets the attribute value o[chars]++; } else { o[chars] = 1; } } console.log(o); // 2. Traversing objects var max = 0; var ch = ""; for (var k in o) { // k is the attribute name // o[k] gets the attribute value if (o[k] > max) { max = o[k]; ch = k; } } console.log(max); console.log("The maximum number of characters is" + ch);
##### String operation method String through the basic wrapper type, you can call some methods to operate the string. The following are some operation methods:[External chain picture transfer...(img-tsNFuMMA-1627031876340)]
// String operation method // 1. concat('string 1 ',' string 2 '...) var str = 'andy'; console.log(str.concat('red')); // andyred // 2. substr('intercept start position ',' intercept several characters'); var str1 = 'The spring breeze of reform is blowing all over the ground'; // The first 2 is the 2 of the index number, starting from the second 2, and the second 2 is the number of characters console.log(str1.substr(2, 2)); // spring breeze
- **replace()method** - - replace() Method is used to replace some characters with others in a string. Its format is as follows:
character string. Replace (string to be replaced, string to be replaced with);
- **split()method** - - split()Method is used to segment a string. It can segment a string into an array. After segmentation, a new array is returned. - Its format is as follows:
character string. split("split character")
// 1. Replace character replace('replaced character ',' replaced character ') it replaces only the first character
var str = "andyandy";
console.log(str.replace("a", "b")); // bndyandy
//There is a string 'abcoefoxyozzopp' that requires all o's in it to be replaced by*
var str1 = "abcoefoxyozzopp";
while (str1.indexOf("o") !== -1) {
str1 = str1.replace("o", "");
}
console.log(str1); // abcefxyzz*pp// 2. Convert characters to array split('separator ') // We learned earlier that join converts an array into a string var str2 = "red, pink, blue"; console.log(str2.split(",")); //[red,pink,blue] var str3 = "red&pink&blue"; console.log(str3.split("&")); // [red,pink,blue]
-