Hierarchy of knowledge architecture:
- Grammar – Morphology – Grammar
- The semantic
- Runtime – Type – Execution procedure
Syntax and semantics are expressions, statements, functions, objects, modules, and types include objects, numbers, strings, and so on…
The knowledge system
HTML and CSS
Browser implementation principles and apis
Front-end engineering practice
JavaScript Types: What details about types do you not know?
The eight language types are: Undefined; Null; Boolean; The String; Number; Symbol; Object, bigInt.
Undefined, Null,
Why do some programming specifications require void 0 instead of undefined? Because JavaScript code uses undefined as a variable rather than a keyword, which is one of the most recognized design mistakes of the JavaScript language, we recommend using void 0 to get undefined to avoid inadvertent tampering.
JavaScript Objects: Object-oriented or object-based?
The JavaScript standard defines object-based: “The language and host infrastructure are provided by objects, and a JavaScript program is a collection of objects that communicate with each other.”
In his book Object-oriented Analysis and Design, Grady Booch summed it up for us by arguing that, from a human cognitive perspective, objects should be one of the following:
- Something that can be touched or seen;
- Something intelligible to the human mind;
- Something that directs thought or action (imagining or performing an action). With a natural definition of an object, we can describe objects in a programming language. In different programming languages, designers also use a variety of language features to describe objects abstractly. The most successful school is the use of “class” to describe objects, which gives birth to popular programming languages such as C++, Java and so on. JavaScript, on the other hand, took an even less popular approach in its early years: prototyping. That’s one of the reasons I said earlier that it doesn’t fit in.
Characteristics of JavaScript objects
- Objects are uniquely identifiable: even if two objects are exactly the same, they are not the same object.
- Stateful: Objects have states. the same object may be in different states.
- An object has behavior: that is, the state of the object may change because of its behavior. In JavaScript, the state and behavior of an object are abstracted as properties. If you’ve ever used Java, don’t be surprised that, despite the differences in design, both nicely represent the basic characteristics of objects: identity, state, and behavior.
On the basis of realizing the basic characteristics of objects, I think that objects in JavaScript are unique in that they are highly dynamic because JavaScript gives users the ability to add state and behavior to objects at run time.
Two classes of properties for JavaScript objects
Data attributes have four characteristics.
- Value: indicates the value of the attribute.
- Writable: Determines whether a property can be assigned a value.
- Enumerable: Determines if for in can enumerate this property.
- Different: Determines whether the property can be deleted or changed.
Accessor (getter/setter) properties, which also have four characteristics.
- Getter: Function or undefined, called when fetching a property value.
- Setter: function or undefined, called when setting property values.
- Enumerable: Determines if for in can enumerate this property.
- Different: Determines whether the property can be deleted or changed.
The code that normally defines a property creates a data property. Writable, Enumerable, and different default is true. We can look at it using the built-in function getOwnPropertyDescriptor. If we want to change the characteristics of a property, or define accessor properties, we can use Object.defineProperty.
You can even see why JavaScript is not object-oriented. This is because the object design of JavaScript is very different from the current mainstream class-based object orientation.
The JavaScript language standard also explicitly states that JavaScript is an object-oriented language, and I think the standard says so, because of JavaScript’s highly dynamic object system.
In some debates, it has been emphasized that JavaScript is not an “object-oriented language”, but an “object-based language”. This idea is cleared. JavaScript itself is object-oriented, it doesn’t need emulation, it just doesn’t implement object-oriented in the same way as the mainstream genre, so many people get the wrong idea.
JavaScript Objects: Do we really need mock classes?
In fact, I don’t think “class-based” is the only form of object orientation, and if we look away from “class,” the prototype system Brendan chose back then is an excellent form of abstract objects.
What is a prototype?
- If all objects have private fields [[prototype]], that is the prototype of the object.
- Reads a property, and if the object itself does not have one, continues to access the object’s prototype until it is empty or found.
But since ES6, JavaScript has provided a number of built-in functions that allow more direct access to manipulating prototypes. The three methods are as follows:
-
Create Creates a new Object based on the specified prototype. The prototype can be null.
-
Object.getprototypeof Gets the prototype of an Object;
-
Object.setPrototypeOf Sets the prototype of an Object.
var cat = { say(){ console.log(“meow~”); }, jump(){ console.log(“jump”); }}
var tiger = Object.create(cat, { say:{ writable:true, configurable:true, enumerable:true, value:function(){ console.log(“roar!” ); }}})
var anotherCat = Object.create(cat);
anotherCat.say();
var anotherTiger = Object.create(tiger);
anotherTiger.say();
However, in earlier versions, the programmer could only manipulate the prototype runtime through a Java-style class interface, which was awkward. Given that infrastructure such as the New and Prototype attributes are still in place today and are used by a lot of code, and that learning about them can help us understand how prototypes work at runtime, let’s take a look back to the early days of JavaScript with stereotypes and classes.
Classes and prototypes in earlier versions
In earlier versions of JavaScript, the definition of a “class” was a private attribute [[class]], and the language standard specified a [[class]] attribute for built-in types such as Number, String, Date, and so on to represent their classes. The only language users can access the attributes of the [[class]] is the Object. The prototype. ToString. As a result, in ES3 and previous versions, the concept of a class in JS is quite weak, and is simply a string property of the runtime.
At the beginning of the ES5, [[class]] private property is Symbol. ToStringTag instead, Object. The prototype. The toString meaning from the name is no longer associated with the class. We can even custom Object. The prototype. ToString behavior, the following code shows the use of Symbol. ToStringTag from definition
The new operation, which takes a constructor and a set of call parameters, actually does several things:
- Create a new object based on the constructor’s Prototype property (note the distinction with the private field [[prototype]]).
- Pass this and the call arguments to the constructor, and execute;
- If the constructor returns an object, otherwise the object created in the first step is returned.
Thanks to the new class/function quirks, I recommend using ES6 syntax to define classes in any scenario. Function returns to its original function semantics. This in subclasses and superclasses is superclass;
## JavaScript Objects: Do you know all the object categories? We can classify objects into several classes.
- Host Objects: Objects provided by the JavaScript host environment whose behavior is entirely determined by the host environment.
- Built-in Objects: Objects provided by the JavaScript language.
- Intrinsic Objects: Instances of Objects that are automatically created as JavaScript runtime is created, as specified by the standard.
- Native Objects: Objects that can be created by the user using built-in constructors such as Array, RegExp, or special syntax.
- Ordinary Objects: Objects created by the {} syntax, the Object constructor, or the class keyword definition class that can be inherited by stereotypes.
Host object BOM
A native object is an instance of an object that is automatically created as the JavaScript runtime creates it, as specified by the standard.
Native objects are created before any JavaScript code is executed, and they often act like base libraries. The “class” we mentioned earlier is actually a class of inherent objects. The ECMA standard provides us with a list of more than 150 inherent objects.
We refer to JavaScript objects that can be created using the language’s own constructor as native objects.
In fact, JavaScript reserves a private field mechanism for this class of objects and specifies the abstract concept of function and constructor objects. A function object is defined as an object with a [[call]] private field. A constructor object is defined as an object with a [[call]] private field.
It is important to note that functions created by the => syntax after ES6 are just functions. They cannot be used as constructors. [[call]] and [[[construct]] always behave similarly to objects created by users using the function syntax or the function constructor. They execute the same piece of code.
JavaScript Execution (1) : Why does the Promise code execute before setTimeout?
Using JSC engine terminology, we refer to host-initiated tasks as macro tasks and JavaScript engine initiated tasks as micro tasks.
Macro and micro tasks
The JavaScript engine waits for the host environment to assign a macro task. In the operating system, the waiting behavior is usually an event loop, so in Node terminology, this part is also referred to as an event loop.
Promise
Promise is a standardized asynchronous management method provided by the JavaScript language. The general idea is that functions that require IO, wait, or other asynchronous operations do not return real results, but instead return a “Promise” that the caller can, at the appropriate time, Choose to wait for the Promise to be fulfilled (via a callback from the Promise’s then method).
New feature: async/await
Async /await is a new feature in ES2016 that provides a way to write asynchrons with code structures such as for and if. Its runtime base is Promise, so with this relatively new feature in mind, let’s take a look at its basic usage. Async functions must return promises, and we consider all functions that return promises to be asynchronous functions. An async function is a special syntax that typically precedes the async keyword before the function keyword, thus defining an async function in which we can await a Promise with await.
JavaScript Execution (2) : What are closures and execution contexts?
‘It’s not hard to find the corresponding closure component in JavaScript based on the classical definition.
- Part of the environment
- Context: the lexical context of a function (part of the execution context)
- Identifier list: Undeclared variables used in a function
- At this point, we can assume that functions in JavaScript fully conform to the definition of closures. Its context is the lexical context of the function, its list of identifiers is the undeclared variables used in the function, and its expression part is the function body. A common misconception here is that some people think of the JavaScript execution context, or Scope (part of the execution context specified in ES3), as a closure. In fact, the JavaScript equivalent of a closure is the concept of “function”. Perhaps this concept is so generic that it doesn’t seem to have much to do with closures, so people unconsciously refer to this concept as the more special-looking “scope”
Execution context: Execution infrastructure
The JavaScript standard defines all the information needed to execute a piece of code (including functions) as “execution context.” The execution context, in ES3, consists of three parts.
- A scope chain is also called a scope chain.
- Variable object: a variable object used to store variables.
- This value: This value. In ES5, we improved the naming by changing the first three parts of the execution context to look like this.
- Lexical environment: lexical environment, used when fetching variables.
- Variable environment: used when declaring variables.
- This value: This value. In ES2018, the execution context is again like this, subsumed by the lexical Environment, but with a few additions.
- Lexical environment: lexical environment, used when fetching variables or this values.
- Variable environment: used when declaring variables.
- Code Evaluation State: Used to restore the code execution location.
- Function: used when the task being executed is a Function.
- ScriptOrModule: used when executing a ScriptOrModule, indicating the code being executed.
- Realm: Base libraries and built-in object instances to use.
- Generator: Only the Generator context has this property, indicating the current Generator.
JavaScript Execution (3) : Do you know how many functions there are now?
In JavaScript, the primary context switch scenario is function calls.
function
- First, ordinary functions: functions defined with the function keyword.
- Second, arrow functions: functions defined with the => operator.
- Third, methods: functions defined in class.
- Fourth, generator functions: functions defined with function *.
- Fifth, classes: classes defined by class are actually functions.
- Sixth/seventh/eighth, asynchronous functions: normal functions, arrow functions, and generator functions with the async keyword.
For ordinary variables, there is no essential difference between these functions. They all follow the rules of “inheritance defined in the context”. One difference in their behavior is the this keyword.
Behavior of this keyword
This is an important part of the execution context. The value of this varies depending on how the same function is called.
function showThis(){
console.log(this);
}
var o = {
showThis: showThis
}
showThis(); // global
o.showThis(); // oss
Copy the code
In this example, we define the function showThis, we assign it to the property of an object O, and then try to call the same function with two separate references, resulting in different values of this.
The this value of an ordinary function is determined by the “Reference used to call it.” The trick is this: when we take the expression of a function, it actually returns not the function itself, but a Reference type (one of the seven standard types we covered in the types chapter).
The Reference type consists of two parts: an object and an attribute value. It is easy to understand the Reference type generated by O.Shothis, which consists of the object O and the attribute “showThis”.
For arithmetic operations (and other operations), the Reference type is dereferenced, that is, the actual value is retrieved to participate in the operation, and operations such as function calls and DELETE require objects in the Reference type.
In this example, the object of the Reference type is passed as this into the context in which the function is executed.
At this point, our interpretation of this is pretty clear: the reference used when a function is called determines the value of this at the time the function is executed.
Mechanism of this keyword
In the JavaScript standard, functions are provided with private attributes [[Environment]] that hold the context in which they are defined. When a function executes, a new execution environment record is created, and the outer lexical environment of the record is set to the function’s [[environment]]. This action is the context switch
When a function is called, a new execution context is pushed, and when the function call ends, the execution context is pushed off the stack. While this is a more complex mechanism, the JavaScript standard defines the [[thisMode]] private property. The [[thisMode]] private attribute has three values.
- Lexical: instantiating finds this from the context, which corresponds to the arrow function.
- Global: indicates that when this is undefined, the global object is taken, corresponding to ordinary functions.
- Strict: Used in strict mode. This is strictly based on the value passed in at the time of the call, which may be null or undefined.
The built-in function that operates on this
Function.prototype.call and function.prototype. apply can specify the this value passed in when a Function is called. There is function.prototype. bind, which generates a bound Function whose this value fixes the argument.
If you put a return inside a try, finally will be executed?
JavaScript statement execution. We use a standard type: Completion Record.
Completion Record represents the result of a statement execution and has three fields:
- [[type]] indicates the type of completion, including break continue return throw and normal.
- [[value]] represents the return value of the statement, or empty if the statement does not have one;
- [[target]] represents the target of the statement, usually a JavaScript tag (the tag is described later). JavaScript relies on the Completion Record type of the statement to implement controls within the complex nested structure of the statement.
Classification of statements:
General statement
In JavaScript, we refer to statements without control as plain statements. There are several common statements.
- Declarative class statement
- The var statement
- Const statement
- Let the statement
- Function declaration
- Class declaration
- Expression statement
- An empty statement
- The debugger statement
After the normal statement is executed, a Completion Record with [[type]] as normal is obtained. The JavaScript engine will proceed to the next statement when it finds such a Completion Record.
block
A statement block is a group of statements enclosed in braces. It is a compound structure of statements that can be nested. The statement block itself is not complicated. It is important to note that if the [[type]] of the Completion Record inside the statement block is not normal, subsequent statement execution of the statement block will be interrupted.
Control statement
Control statements take the if and switch keywords, which react to different types of Completion Records.
The control statements are divided into two parts. One is the internal impact, such as if, switch, while/for, and try. The other is the external impact such as break, continue, return and throw. The coordination of these two types of statements will control the sequence and logic of code execution, which is also the main work of our programming.
Tagged statements
The only time this works is when it is used in conjunction with the target in the completion record type to break out of a multi-level loop. The break/continue statement, if followed by a keyword, produces a completion record with target. Once the completion record carries a target, only loop statements with the corresponding label consume it.
JavaScript Syntax: Why is 12.toString an error?
Next, let’s look at the grammar part of JavaScript.
Grammar is a provision of the compilation principle for the writing of language. Generally speaking, grammar is divided into two types: morphology and grammar.
Lexical analysis techniques can be performed using state machines or regular expressions.
- Input in JavaScript source code can be classified as follows:
- WhiteSpace WhiteSpace characters
- LineTerminator newline
- The Comment annotation
- Token word
- IdentifierName IdentifierName, typically the name of the variable we use. Note that keywords are included here as well. – Punctuator symbol, the operator and braces we use.
- A NumericLiteral number is the number we write.
- StringLiteral literal is the literal quantity that we use with single or double quotation marks.
- Template String Template, the immediate quantity enclosed in backquotes.
Understand how compilation works: a four-operation interpreter
- Define four operations: Produce lexical and syntactic definitions for four operations.
- Lexical analysis: Turn the input string stream into tokens.
- Parsing: Turn tokens into abstract syntax tree AST.
- Explain execution: Iterate through the AST in sequence and execute the result.
JavaScript Syntax (Prep) : Should I write a semicolon or not?
Auto insert semicolon rule
The autoinsert semicolon rule is independent of all syntactic production definitions, and its rules are very simple, with only three.
- To have a newline character, and the next symbol is ungrammatical, try to insert a semicolon.
- If there is a newline character, and the syntax says no newline character, the semicolon is automatically inserted.
- At the end of the source code, if the complete script or module structure cannot be formed, the semicolon is automatically inserted.
Why is it wrong to write export in script tag?
Scripts and modules
First, JavaScript comes in two types of source files, one called scripts and one called modules. This distinction began with the introduction of modules in ES6, and in ES5 and prior releases, there was only one source file type (only scripts).
Scripts can be imported into execution by the browser or node environment, whereas modules can only be imported into execution by JavaScript code using import.
JavaScript Syntax (2) : Which JavaScript statements do you know?
What is an expression statement?
An expression statement is essentially an expression that consists of operators concatenating variables or direct quantities.
PrimaryExpression PrimaryExpression
First let’s show you the atomic term of an Expression: Primary Expression. It is the smallest unit of an expression, and the syntactic structure involved is of the highest priority. Such as’ ABC ‘, 123 and so on.
MemberExpression MemberExpression
Member Expression is usually used to access object members. It takes several forms: a.b. A (” b “), new.target; super.b;
NewExpression NEW expression
Member Expression plus new is new Expression (of course, new Expression can also be formed without new, and default independent high-priority expressions in JavaScript can be formed low-priority expressions).
CallExpression Specifies the expression used to call functions
. The basic form is Member Expression followed by a list of arguments in parentheses, or we can use the super keyword instead of Member Expression.
LeftHandSideExpression Lvalue expression
New Expression and Call Expression are collectively called LeftHandSideExpression, an lvalue Expression.
IgnmentExpression Assignment expression
AssignmentExpression can take many forms, the most basic of which is, of course, the use of the equal sign.
HTML semantics: Aren’t div and SPAN enough?
What is a semantic class tag, and what are the benefits of using it?
Semantic tags are also commonly used in your work. They are visually similar to each other. The main difference is that they represent different semantics, such as section, nav and P, which you will often see.
- Semantic tags are more developer-friendly. Using semantic tags increases readability, allowing developers to clearly see the structure of a web page even without CSS, making it easier for teams to develop and maintain.
- In addition to being human-friendly, semantic tags are also great for machine reading. Its rich text expression, more suitable for search engine search (SEO), can also make search engine crawler better access to more effective information, effectively enhance the search volume of the web page, and semantic class can also support screen reading software, according to the article can automatically generate directories and so on.
CSS syntax: In addition to properties and selectors, you also need to know the @ rules
The top-level style sheet of CSS consists of a rule list consisting of two types of rules, one is called at-rule, or AT rule, and the other is qualified rule, or common rule.
HTML meta information tags: Do you know how many tags can be in head?
Meta information refers to information that describes itself. Meta information tags are the types of tags that HTML uses to describe a document itself. They usually appear in the head tag and are not normally displayed on the page (as opposed to other tags, such as semantic tags, that describe the business).
The head tags
First, let’s look at the head tag. The head tag doesn’t carry any information on its own. It’s used primarily as a container for other semantic class tags.
The title tag
The title tag represents the title of the document.
The base label
Its purpose is to provide a basis for all URL relative addresses on the page. There is at most one base tag, which changes the global link address.
Meta tags
A meta tag is a set of key-value pairs. It is a generic meta information representation tag. Any number of meta tags can appear in the head. A typical meta tag is defined by the name and Content attributes. Name indicates the name of the meta information, and Content indicates the value of the meta information.
CSS selectors: What about fake elements?
A pseudo-element is not only a selection rule in itself, it is also a mechanism. The syntax of pseudo-elements is similar to that of pseudo-classes, but the actual effect is to force out non-existent elements. The following pseudo-elements are currently compatible enough to be available. ::first-line::first-letter::before::after
Next we talk about ::before and ::after pseudo-elements.
::before means to insert a dummy element before the element content, and ::after means to insert after the element content. The CSS rules for these two pseudo-elements must specify the content property for this to work. Here’s an example:
<p class="special">I'm real element</p>
p.special::before {
display: block;
content: "pseudo! ";
}
Copy the code
HTML Links: Besides the A tag, what other tags are called links?
CSS typography: we have been using normal flow since Bisheng
The principle of normal flow
In the CSS standard, the algorithm for how to arrange each text or box depends on a typesetting ‘current state’, which CSS refers to as a ‘formatting context’. We can think of the typesetting process as follows:
Formatting context + box/text = position The boxes we need to type are divided into block level boxes and inline level boxes, so formatting needs to specify block level formatting context and inline level formatting context for them respectively. When we want to type a box or text in normal flow, we need to deal with three cases.
- When block-level boxes are encountered: exhaust the block-level formatting context.
- When encountering inline boxes or text: first try to type in the inline formatting context, if not, then create a line box, first type the line box (line box is block level, so to the first case), the line box will create an inline formatting context.
- Encountering a float box: Align the top of the box with the upper edge of the current inline context, then align the corresponding edge of the box to the edge of the block-level formatting context based on the float orientation, and then rearrange the current row box.
The layout of a page is not that simple. Some elements create new block-level formatting contexts within the page. These elements include:
- Floating element;
- Absolute positioning element;
- Non-block-level containers that can still contain block-level elements (such as inline-blocks, table-cells, table-captions);
- A block-level container that can contain block-level elements, and the property overflow is not visible.
HTML replacement elements: why link a CSS using href, but import js using SRC?
Substitution elements refer to the file using the SRC attribute, whereas linked elements, as we’ve seen in previous lectures, use the href tag. I don’t know how it was designed, but the style tag is not a replacement element and cannot use the SRC attribute, so we use the link tag to import the CSS file, using the href tag of course.
CSS Flex Typography: Why is vertical centering So hard?
React Native takes the bold step of using pure Flex typography, no longer supports normal flow, and ultimately does a good job of supporting a wide range of application layouts, proving Flex typography’s potential.
The design of the Flex
At the heart of Flex typography are display: Flex and Flex properties, which work together. An element with display: Flex is called a Flex container, and its child elements or boxes are called Flex items.
CSS Animation and Interaction: Why do animations use Such strange things as Bezier curves?
CSS has two animation-related properties: animation and Transition.
@keyframes mykf { from {background: red; } // or percentage sign to {background: yellow; } } div { animation:mykf 5s infinite; }Copy the code
The basic usage of animation is shown here. Animation is actually divided into six parts:
- Animation-name specifies the name of the animation, which is a value for keyframes (as we explained in section 9, “CSS syntax: in addition to properties and selectors, you need to know the @ rules”). Keyframes generate the data used to define the animation keyframes.
- Animation-duration Specifies the duration of the animation.
- Animation-timing-function Time curve of the animation;
- Animation-delay Indicates the delay before the animation starts.
- Animation-rotund-count Specifies the number of times an animation is played;
- Animation-rotund-count Specifies the number of times an animation is played;
So let’s talk about transition. Compared to animation, transition is a much simpler property.
- Transition-property Specifies the property to be transformed.
- Transition-duration Duration of transformation;
- Transition-timing-function Time curve;
- The transition – delay delay.
Browsers: How does a browser work? (Stage 1)
HTTP Status code and Status text
Next let’s look at the status code and status text of the Response line. Common status codes are as follows.
- 1xx: Temporary response, indicating that the client please continue.
- 2xx: The request succeeded.
- 200: Request succeeded.
- 3xx: indicates that the target of the request has changed and the client is expected to further process it.
- 301&302: Permanent and temporary jumps.
- 304: The client cache is not updated.
- 4xx: The client request is incorrect.
- 403: No permission.
- 404: The requested page does not exist.
- This is a teapot. This is an Easter egg, from an April Fool’s Joke by IETF. (Hypertext Coffee maker control Protocol)
- 5xx: The server requests an error.
- 500: server error.
- 503: Server has a temporary error. You can try again later.
The Request Header.
Response Header
HTTP Request Body
- application/json
- application/x-www-form-urlencoded
- multipart/form-data
- text/xml
Browsers: How does a browser work? (Stage 2)
Browser DOM: Do you know what types of HTML nodes are?
The DOM API generally consists of four parts.
- Nodes: Node-related apis in the DOM tree.
- Event: Triggers and listens to event-related apis.
- Range: Apis for manipulating text ranges.
- Traversal: Traverses the API required by the DOM.
node
DOM tree structure all nodes have a unified interface Node, we according to the inheritance relationship, to introduce to you the type of Node.
Node
Node is the root Node of the DOM tree inheritance relationship. It defines the DOM Node’s operations on the DOM tree. First, Node provides a set of properties that represent its relationships in the DOM tree.
- parentNode
- childNodes
- firstChild
- lastChild
- nextSibling
- previousSibling
Node also provides apis for manipulating DOM trees, including the following.
- appendChild
- insertBefore
- removeChild
- replaceChild
Node also provides some high-level apis, so let’s take a look at them.
- CompareDocumentPosition is a function that compares the relationship between two nodes.
- Contains a function that checks whether a node contains another node.
- IsEqualNode checks whether two nodes are identical.
- IsSameNode checks if two nodes are the same node, and actually uses “===” in JavaScript.
- CloneNode copies a node and, if true is passed, makes a deep copy along with the child elements.
The DOM standard states that nodes must be created from the document’s create method and cannot use the native JavaScript new operation. So the Document object has these methods.
- reateElement
- createTextNode
- createCDATASection
- createComment
- createProcessingInstruction
- createDocumentFragment
The Element and Attribute
Element represents an Element and is a subclass of Node. The element corresponds to the tag in HTML and has both child nodes and attributes. So Element subclasses have a set of methods for manipulating attributes. First, we can treat the Attribute of an element as if it were a string, so we have the following API:
- getAttribute
- setAttribute
- removeAttribute
- hasAttribute
Look for the element
The document node provides the ability to find elements. There are, for example, the following.
- querySelector
- querySelectorAll
- getElementById
- getElementsByName
- getElementsByTagName
- getElementsByClassName
Browser CSSOM: How do I get the exact location of an element
As the name suggests, CSSOM is the object model of CSS. According to the W3C standard, it contains two parts: the model part (CSSOM), which describes CSS stylesheets and rules, and the View part (CSSOM View), which is related to element views.
Let’s start by looking at the basic usage of the CSSOM API. In general, we need to get all the stylesheets in the document first:
document.styleSheets
Copy the code
We cannot create a stylesheet using the CSSOM API, but we can modify the content of the stylesheet.
document.styleSheets[0].insertRule("p { color:pink; }", 0)
document.styleSheets[0].removeRule(0)
Copy the code
Further, we can take a particular Rule from the stylesheet and do something with it, specifically using its cssRules property:
document.styleSheets[0].cssRules
Copy the code
We’ve compiled a complete list of at-rules for you in the CSS syntax section. Most at-rules correspond to one rule type:
- CSSStyleRule
- CSSCharsetRule
- CSSImportRule
- CSSMediaRule
- CSSFontFaceRule
- CSSPageRule
- CSSNamespaceRule
- CSSKeyframesRule
- CSSKeyframeRule
- CSSSupportsRule
CSSStyleRule has two properties, selectorText and style, which represent the selector part and style part of a rule, respectively.
The selector part is a string, so we’re obviously lazy here in not designing a further selector model, so we’ll just follow the selector syntax.
The Style section is a style sheet, which is of the same type as the style property of our element, so we can change the specific CSS property definition in the property modification rule directly, just as we changed the inline style, or we can use utility properties like cssText.
CSSOM also provides a very important method for obtaining the final CSS evaluation of an element’s properties:
window.getComputedStyle(elt, pseudoElt);
Copy the code
CSSOM View
The CSSOM View API can be viewed as an extension of the DOM API. It adds display-related functions to the original Element interface. These functions can be divided into three parts: window, scroll and layout.
Windows API
The window API is used to manipulate the position, size, and so on of the browser window.
- The moveTo(X, Y) window moves to specific coordinates of the screen;
- MoveBy (x, y) window moves a certain distance
- ResizeTo (x, y) Change the window size to a specific size;
- ResizeBy (x, y) changes the window size to a specific size.
In addition, the window API specifies a third argument to window.open() :
window.open("about:blank", "_blank" ,"width=100,height=100,left=100,right=100" )
Copy the code
Scroll to the API
Viewport scrolling API
The viewport scrolling behavior is controlled by a set of apis on the Window object. Let’s start with:
- ScrollX is an attribute of the viewport, representing the current scrolling distance in the X direction, alias pageXOffset;
- ScrollY is an attribute of the viewport, which represents the current scrolling distance in the Y direction and has the alias pageYOffset.
- Scroll (x, y) makes the page scroll to a specific position, has the alias scrollTo, supports the configuration parameter {top, left};
- ScrollBy (x, y) makes the page scroll a specific distance, support the incoming type configuration parameters {top, left}.
Element scrolling API
Let’s take a look at the Element scrolling API. In the Element class (see the DOM section), the following API is added to support scrolling.
- Property of the scrollTop element that represents the current scrolling distance in the Y direction.
- Property of the scrollLeft element that represents the current scrolling distance in the X direction.
- Property of the scrollWidth element, indicating the width of the scrolling content inside the element, which is generally greater than or equal to the element width.
- ScrollHeight Element property, indicating the height of the scrolling content inside the element, generally greater than or equal to the element height.
- Scroll (x, y) to scroll an element to a specific position, alias scrollTo, and support passing in the configuration parameter {top, left}.
- ScrollBy (x, y) makes the rolling element to a specific location, support the incoming type configuration parameters {top, left}.
- ScrollIntoView (ARG) scrollIntoView(ARG) scrollIntoView(ARG) scrollIntoView(ARG) scrollIntoView(ARG) scrollIntoView(ARG) scrollIntoView(ARG) scrollIntoView(ARG) scrollIntoView(ARG)
The layout of the API
Global size information
- The window.innerHeight and window.innerWidth properties represent the viewport size.
- The window.outerWidth and window.outerHeight properties indicate the size of the browser window. Many browsers don’t implement these properties and generally they don’t matter.
- The window. DevicePixelRatio property is very important. It represents the ratio of the physical pixel to the CSS pixel unit.
- Window.screen (Information about screen size)
- Window.screen. width, window.screen.height Screen size of the device.
- Window. Screen. AvailWidth, window. Screen. AvailHeight equipment can apply colours to a drawing of the screen area size, some Android machine will do the part of the screen set aside a fixed button, so have these two properties, In fact, most browsers don’t do this.
- Window. The screen. The colorDepth, window. Screen. PixelDepth 24, these two properties is a fixed value should be reserved for later.
Can we get the width and height of an element? In fact, the first thing we should do is eliminate the idea that elements have width and height from our minds. We have already mentioned several times that some elements can have multiple boxes. In fact, only boxes have width and height, but elements do not.
So the object we get the width and height should be a box, so CSSOM View adds two methods to the Element class:
- getClientRects();
- GetBoundingClientRect (). GetClientRects returns a list of client rectangles occupied by each box of the element, where each rectangle can be positioned and sized using x, y, width, height.
The getBoundingClientRect API is designed to be more like the box in our mind. It returns the rectangular region of all boxes that the element corresponds to. Note that the region retrieved by this API includes the subelement region when Overflow is visible.