Reprint please indicate the source: github.com/qiu-deqing/…

Table of Contents generated with DocToc

  • FE-interview
    • $HTML, HTTP, Web integration issues
      • Time complexity and space complexity of common sorting algorithms
      • What SEO does the front end need to pay attention to
      • What are the methods of session tracing in Web development
      • <img>thetitleandaltWhat’s the difference?
      • What is a doctype? Examples of common doctypes and features
      • What are HTML global attributes
      • What is Web semantics and what are the benefits
      • HTTP method
      • Steps from entering a URL from the browser address bar to displaying the page (using HTTP as an example)
      • What is the structure of an HTTP request packet
      • What is the structure of HTTP Response packets
      • How to optimize website performance
      • What is progressive enhancement
      • HTTP status code and its meaning
    • $CSS part
      • What are the CSS selectors
      • What is CSS Sprite, and what are its pros and cons
      • display: none;withvisibility: hidden;The difference between
      • CSS hack principle and common hack
      • Specified Value,computed Value, and used value methods
      • linkwith@importThe difference between
      • display: block;anddisplay: inline;The difference between
      • PNG,GIF,JPG difference and how to choose
      • What are the inherited properties of the CSS
      • What are the common bugs, defects, or standard inconsistencies in IE6? How to solve them
      • How do I clean up floating elements when a container contains several floating elements
      • What is a FOUC? How to avoid
      • How to create block formatting contexts and what is the use of BFC
      • The display, float, the relationship between the position
      • Collapsing margins
      • How to determine the containing block of an element
      • Stacking context, layout rules
      • How to center an element horizontally
      • How do I center an element vertically
    • $javascript concept section
      • What is the difference between E.tropName and E.lldb (propName) for DOM element E
      • OffsetWidth/offsetHeight, clientWidth/clientHeight scrollWidth/scrollHeight difference
      • XMLHttpRequest Generic properties and methods
      • Differences and connections between Focus /blur and focusin/focusout
      • Mouseover /mouseout/MouseEnter /mouseleave
      • SessionStorage and localStorage, cookies
      • Javascript communicates across domains
      • How many data types do javascript have
      • What closure? What’s a closure for
      • How many ways does javascript define functions
      • Application storage and offline Web applications
      • The client stores localStorage and sessionStorage
      • Cookies and their operations
      • What methods does javascript have to define objects
      • How does the === operator determine equality
      • What is the flow of the == operator to determine equality
      • Object to string conversion steps
      • Object to number conversion steps
      • <,>,<=,>= comparison rules
      • + operator workflow
      • What are the properties of the arguments variable inside the function? How do I convert it to an array
      • What about the DOM event model and writing an EventUtil utility class for event management compatibility
      • Evaluate the advantages and disadvantages of the three approaches to inheritance and make improvements
    • $javascript programming section
      • Please use native JS to implement a function to add a transparent mask (variable transparency, default 0.2) to any element of the page to make this area click invalid. It is required to be compatible with IE8+ and all major browsers. The mask layer effect is as shown below:
      • Please write in code (today is Monday x) where x is the day of the week, if it is Monday, the output should be “Today is Monday”.
      • The following code wants to loop delay output 0, 1, 2, 3, 4. Is the output correct? If not, please explain why and modify the code inside the loop to output the correct result
      • You have a Page class whose prototype object has a number of methods (such as postMsg) that start with POST; Please design a function that will batch modify the original Page postXXX method, while preserving its original function, add interception validation for each postXXX method, when chekc returns true, continue to execute the original postXXX method. The original postXXX method is no longer executed when false is returned
      • Complete the tool-tip below
      • Write javascript deepClone function deepClone
      • Add code to move Button1 behind Button2 after mouse click on Button1
      • Web page to realize a calculation of how much time left in the year countdown program, requiring the webpage real-time dynamic display of “×× year left ×× days ×× hours ×× minutes ×× seconds”
      • Completes a function that takes an array of integers or arrays and returns a flattened array
      • How do I determine if an object is an array
      • Please review the following event listener code and suggest improvements
      • How do YOU tell if an object is a function
      • Write a function that takes a QUERY String in the URL as an argument and returns a parsed Object. The Query String is coded using Application/X-www-form-urlencoded
      • Parses a complete URL and returns Object containing the same field as window.location
      • The completion function getViewportSize returns the viewport size of the specified window
      • The completion function getScrollOffset returns the window scroll bar offset
      • You have a string, richText, which is richText that needs to be displayed on the page. There is a requirement to add a class called PIC to the p tag that contains only one IMG element. Please write code to implement. You can use jQuery or KISSY.
      • Implement an Event class. Objects that inherit from this class will have two methods: on,off,once, and Trigger
      • Write a function to reverse the order of the list’s children
      • What does the following function do? What should be filled in the blank area
      • Write a function to serialize a form (that is, serialize the key values in a form into a committable string)
      • Use native javascript to bind the click event to the li node in the list below, creating an Object when clicked, compatible with IE and standard browsers
      • Var a = [‘1’, ‘2’, ‘3’… ; The length of a is 100 and the content is a string filled with random integers. Construct the array A first, and then design an algorithm to deduplicate its contents

Personal collection of front-end knowledge points, interview questions and answers, the reference answers only represent personal views, easy to review, the catalog is as follows, through the search directory in the document can quickly locate the chapter

$HTML, HTTP, Web integration issues

Time complexity and space complexity of common sorting algorithms

What SEO does the front end need to pay attention to

  1. Reasonable title, description, keywords: search for the weight of the three decreased one by one, the title value can emphasize the key, important keywords should not appear more than 2 times, and to the front, different pages of title to be different; Description summarizes the content of the page, the length is appropriate, not excessive stacking keywords, different page description is different; Keywords list the key keywords
  2. Semantic HTML code that conforms to W3C specifications: semantic code makes it easy for search engines to understand web pages
  3. Important content HTML code in the front: search engines grab HTML order from top to bottom, some search engines have restrictions on the length of the grab, to ensure that important content will be captured
  4. Do not output important content in JS: crawlers do not execute JS to retrieve content
  5. Use iframes sparingly: Search engines do not crawl iframes
  6. Alt must be used for non-decorative images
  7. Improve site speed: Site speed is an important indicator of search engine ranking

What are the methods of session tracing in Web development

  1. cookie
  2. session
  3. The url rewrite
  4. Hidden input
  5. The IP address

<img>thetitleandaltWhat’s the difference?

  1. titleisglobal attributesIs used to provide additional advisory information for the element. Usually displayed when the mouse is slid over an element.
  2. altis<img>Is an equivalent description of the picture content. It is used to display and read the picture when the picture cannot be loaded. Removable images are highly accessible. In addition to pure decorative images, meaningful values must be set, and search engines will focus on analysis.

What is a doctype? Examples of common doctypes and features

  1. <! doctype>The declaration must be in the header of the HTML document, in<html>Before tags, HTML5 is case insensitive
  2. <! doctype>A declaration is not an HTML tag, but an instruction that tells the browser the current version of HTML
  3. Modern browsers’ HTML layout engines examine docTypes to determine whether to render documents in compliant or standard mode, and some browsers have a near-standard model.
  4. In HTML4.01<! doctype>The declaration points to a DTD, and since HTML4.01 is based on SGML, the DTD specifies markup rules to ensure that the browser renders the content correctly
  5. HTML5 is not based on SGML, so you don’t have to specify a DTD

Common dotype:

  1. HTML4.01 strict: Do not allow the use of expressivity, obsolete elements (such as font), and frameset. Statement:<! PUBLIC DOCTYPE HTML "- 4.01 / / / / / / W3C DTD HTML EN" "http://www.w3.org/TR/html4/strict.dtd" >
  2. HTML4.01 Transitional: Expressive, obsolete elements (such as font) are allowed, but frameset is not. Statement:<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" >
  3. HTML4.01 Frameset: Allows expressive elements, exhaust elements, and frameset. Statement:<! PUBLIC DOCTYPE HTML "- / / / / W3C Frameset DTD HTML 4.01 / / EN" "http://www.w3.org/TR/html4/frameset.dtd" >
  4. XHTML1.0 Strict: Don’t use permissibility, scrap elements, or frameset. The document must be a well-formed XML document. Statement:<! PUBLIC DOCTYPE HTML "- / / / DTD/W3C XHTML 1.0 Strict / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
  5. XHTML1.0 Transitional: Expressive, obsolete elements are allowed, frameset is not allowed, and the document must be a well-formed XMl document. Statement:<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
  6. XHTML 1.0 Frameset: Allows the use of expressivity, scrap elements, and Frameset, and the document must be a well-formed XML document. Statement:<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD XHTML 1.0 Frameset / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd" >
  7. HTML 5: <! doctype html>

What are HTML global attributes

Reference: MDN: HTML global Attribute or W3C HTML global-Attributes

  • accesskey: Sets shortcut keys to provide quick access to elements such asaaaIn Firefox on Windows, pressalt + shift + aActivable element
  • class: Sets the class identifier for the element. Multiple class names are separated by Spaces. CSS and javascript can get the element through the class attribute
  • contenteditable: Specifies whether the element content is editable
  • contextmenu: Customizes the right mouse button to display menu contents
  • data-*: Adds custom attributes to an element
  • dir: Sets the element text orientation
  • draggable: Sets whether elements can be dragged
  • dropzone: Sets element drag and drop types: copy, move, link
  • hidden: indicates whether an element is related to a document. The style will cause the element not to be displayed, but you cannot use this property to implement the style effect
  • id: element ID, unique within the document
  • lang: the language of the element content
  • spellcheck: Specifies whether to enable spelling and grammar checking
  • style: inline CSS styles
  • tabindex: Sets the element to get focus and navigation by tabbing
  • title: Suggestion information about the element
  • translate: Whether element and descendant node content needs to be localized

What is Web semantics and what are the benefits

Web semantematization refers to the representation of information contained in a page by HTML tags, including the semantematization of HTML tags and the semantematization of CSS naming. Semantematization of HTML tags refers to: properly representing the structure of a document by using tags that contain semantics (e.g. H1-h6). Semantematization of CSS naming refers to: Add a meaningful class to an HTML tag. Id complements unexpressed semantics. For example, Microformat adds a class description that conforms to the rules.

  • Remove the styling and the page is clearly structured
  • Blind people use screen readers to read better
  • Search engines better understand the page, is conducive to inclusion
  • Responsible for the sustainable operation and maintenance of team projects

HTTP method

  1. A server that is HTTP1.1 compliant simply implements the GET and HEAD methods for resources
  2. GET is the most common method and is usually used to ask the server to send a resource.
  3. HEAD is similar to GET, but the server returns the header in the response, not the body of the entity
  4. PUT lets the server use the body of the request to create a new document named after the requested URL, or, if that URL already exists, replace it with the body
  5. POST was originally used to input data to the server. In fact, it’s often used to support HTML forms. The data filled out in the form is usually sent to the server, which then sends it to where it wants to go.
  6. TRACE initiates a loopback diagnosis at the destination server, and the server at the last station bounces back a TRACE response with the original request message it received in the response body. The TRACE method is primarily used for diagnostics to verify that the request traverses the request/response chain as desired.
  7. The OPTIONS method asks the Web server to tell it what functionality it supports. You can query which methods are supported by the server or which methods are supported for specific resources.
  8. DELETE The request server deletes the resource specified by the request URL

Steps from entering a URL from the browser address bar to displaying the page (using HTTP as an example)

  1. Enter the URL in the browser address bar
  2. Browser viewThe cacheIf the requested resource is in cache and fresh, skip to transcoding step
    1. If the resource is not cached, make a new request
    2. If it is cached, verify whether it is fresh enough and provide it to the client directly. Otherwise, verify with the server.
    3. Checking freshness is usually controlled by two HTTP headersExpiresandCache-Control:
      • HTTP1.0 provides Expires, with a value of an absolute time to indicate a cached fresh date
      • HTTP1.1 added cache-control: max-age=, which is the maximum fresh time in seconds
  3. Browser parse URL fetch protocol, host, port, path
  4. The browser assembles an HTTP (GET) request packet
  5. The browserObtain the HOST IP address, the process is as follows:
    1. Browser cache
    2. This machine is the cache
    3. Hosts file
    4. Router cache
    5. ISP DNS cache
    6. DNS recursive query (different IP addresses may occur due to load balancing)
  6. Open a socket to establish a TCP connection with the destination IP address and portThe three handshakes are as follows:
    1. The client sends a TCP SYN=1, Seq=X packet to the server port
    2. The server sends back a response packet with SYN=1, ACK=X+1, Seq=Y
    3. The client sends ACK=Y+1, Seq=Z
  7. After a TCP connection is established, an HTTP request is sent
  8. The server accepts the request, parses it, and forwards it to a server, such as the virtual Host using the HTTP Host header to determine the requested server
  9. The server checks whether the HTTP request header contains cache authentication information. If the cache is fresh, the server returns the status code, such as 304
  10. The handler reads the complete request and prepares the HTTP response, which may require, for example, querying the database
  11. The server sends the response back to the browser over the TCP connection
  12. The browser receives the HTTP response and selects it based on the situationTo close the TCP connection or keep it for reuse, the four-way handshake for closing the TCP connection is as follows:
    1. The active party sent Fin=1, Ack=Z, Seq= X packets
    2. The passive sends ACK=X+1, Seq=Z packets
    3. The passive sends Fin=1, ACK=X, and Seq=Y packets
    4. The active party sends ACK=Y, Seq=X packets
  13. Does the browser check the response status: 1XX, 3XX, 4XX, 5XX, these cases are handled differently from 2XX
  14. If the resource is cacheable, cache it
  15. Decode the response (for example, gzip compression)
  16. Decide what to do based on the resource type (assuming the resource is an HTML document)
  17. Parsing HTML documents, building DOM trees, downloading resources, constructing CSSOM trees, and executing JS scripts are all in no strict order, as explained below
  18. Build a DOM tree:
    1. Tokenizing: Parsing character streams into tags according to the HTML specification
    2. Lexing: Lexical analysis converts tags into objects and defines attributes and rules
    3. DOM Construction: Organize objects into DOM trees based on HTML tag relationships
  19. Image, style sheet, JS file encountered during parsing, start download
  20. buildCSSOM tree:
    1. Tokenizing: Character stream converted to token stream
    2. Node: Creates a Node based on the tag
    3. CSSOM: The node creates the CSSOM tree
  21. Build the render tree from the DOM tree and the CSSOM tree:
    1. Traversal all from the root of the DOM treeVisible nodes, invisible nodes include: 1)script.metaSo the tag itself is not visible. 2) Nodes hidden by CSS, such asdisplay: none
    2. For each visible node, find the appropriate CSSOM rule and apply it
    3. Publish the content and calculation style of the visual node
  22. Js parsing is as follows:
    1. The browser creates the Document object, parses the HTML, and adds the parsed elements and text nodes to the Document
    2. When the HTML parser encounters scripts without async and defer, it adds them to the document and then executes inline or external scripts. These scripts execute synchronously, and the parser pauses while the script is downloaded and executed. This allows you to insert text into the input stream with document.write(). Synchronous scripts often simply define functions and register event handlers that can iterate and manipulate scripts and their previous document contents
    3. When the parser encounters a script with the async property set, it starts downloading the script and continues parsing the document. The script is executed as soon as it is downloaded, but the parser does not stop for it to download. Document.write () is prohibited for asynchronous scripts, which have access to their own script and previous document elements
    4. When the document is parsed, document.readState becomes interactive
    5. All defer scripts will be executed in the order in which they appear in the document. The deferred script has access to the full document tree, and document.write() is prohibited.
    6. The browser fires the DOMContentLoaded event on the Document object
    7. When the document is fully parsed, the browser may still be waiting for content such as images to load. When that content is loaded and all asynchronous scripts are loaded and executed, document.readState changes to complete and the window fires the load event
  23. Display the page (the page is displayed gradually as the HTML is parsed)

What is the structure of an HTTP request packet

Rfc2616 defines:

  1. The first Line of the request-line contains: Request method, Request URI, protocol version, CRLF
  2. The first line is followed by several lines of request headers, including general-header, request-header, or entity-header, each ending with CRLF
  3. There is a CRLF separation between the request header and the message entity
  4. The following is an example of a request packet that may contain a message entity:
GET/separate Protocols/rfc2616 rfc2616 - sec5. HTTP / 1.1 HTML Host: www.w3.org Connection: keep alive - cache-control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp, * / *; Q =0.8 user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 Referer: https://www.google.com.hk/ Accept-Encoding: gzip,deflate,sdch Accept-Language: zh-CN,zh; Q = 0.8, en. Q =0.6 Cookie: authorstyle=yes if-none-match: "2CC8-3e3073913b100" if-modified-since: authorstyle=yes if-none-match: "2CC8-3e3073913b100" if-modified-since: Wed, 01 Sep 2004 13:24:52 GMT name=qiu&age=25Copy the code

What is the structure of HTTP Response packets

Rfc2616 defines:

  1. The first line is the status line containing: HTTP version, status code, status description, followed by a CRLF
  2. The first line is followed by several lines of response headers, including: generic headers, response headers, and solid headers
  3. A CRLF blank line separates the response header from the response entity
  4. Finally, an example of a possible message entity response message is as follows:
HTTP/1.1 200 OK
Date: Tue, 08 Jul 2014 05:28:43 GMT
Server: Apache/2
Last-Modified: Wed, 01 Sep 2004 13:24:52 GMT
ETag: "40d7-3e3073913b100"
Accept-Ranges: bytes
Content-Length: 16599
Cache-Control: max-age=21600
Expires: Tue, 08 Jul 2014 11:28:43 GMT
P3P: policyref="http://www.w3.org/2001/05/P3P/p3p.xml"
Content-Type: text/html; charset=iso-8859-1

{"name": "qiu", "age": 25}
Copy the code

How to optimize website performance

Yahoo Best Practices for Speeding Up Your Web Site

  • The content in

    1. Reduce HTTP requests: merge files, CSS sprites, inline images
    2. Reduce DNS queries: the browser cannot download any files from this host until DNS queries are complete. Methods: DNS caching, distributing resources to the appropriate number of host names, balancing parallel downloads and DNS queries
    3. Avoid redirects: redundant intermediate access
    4. Make Ajax cacheable
    5. Non-mandatory components are lazily loaded
    6. Future required component preloading
    7. Reduce the DOM element count
    8. Put resources in different domains: Browsers can only download a limited number of resources from one domain at a time, and adding domains can increase parallel downloads
    9. Reduce the number of IFrames
    10. Don’t 404
  • The Server side

    1. Use the CDN
    2. Add the Expires or cache-control response header
    3. Use Gzip compression for components
    4. Configure the ETag
    5. Flush Buffer Early
    6. Ajax uses GET for requests
    7. Avoid empty SRC img tags
  • Cookie aspects

    1. Reduce cookie size
    2. The domain name of the imported resource does not contain cookies
  • CSS aspects

    1. Place the style sheet at the top of the page
    2. Do not use CSS expressions
    3. Use do not use @import
    4. The Filter of IE is not used
  • In Javascript

    1. Place the script at the bottom of the page
    2. Bring in javascript and CSS from the outside
    3. Compress javascript and CSS
    4. Delete unnecessary scripts
    5. Reducing DOM access
    6. Design event listeners properly
  • pictures

    1. Optimize picture: select color depth and compression according to actual color needs
    2. Optimizing CSS Sprites
    3. Do not stretch images in HTML
    4. Make favicon.ico small and cacheable
  • In mobile

    1. Ensure that the component size is smaller than 25 KB
    2. Pack Components into a Multipart Document

What is progressive enhancement

Progressive enhancement refers to the emphasis on accessibility, semantic HTML tags, external style sheets, and scripting at Web design time. Ensure that everyone can access the basic content and functionality of the page while providing a better user experience for advanced browsers and high-bandwidth users. The core principles are as follows:

  • All browsers must be able to access basic content
  • All browsers must be able to use basic functionality
  • All content is contained within the semantic tag
  • Provides enhanced layout through external CSS
  • Provide enhancements through non-invasive, external javascript
  • end-user web browser preferences are respected

HTTP status code and its meaning

Refer to RFC 2616

  • 1XX: indicates the information status code
    • 100 Continue: The client should Continue sending requests. This temporary response is used to inform the client that some of its requests have been received by the server and have not yet been rejected. The client should continue to send the rest of the request, or ignore the response if the request is completed. The server must send a final response to the client on request
    • 101 Switching Protocols: The server has understood the client’s request and will notify the client via the Upgrade header that the request is completed using a different protocol. After sending the blank line at the end of this response, the server will switch to the protocols defined in the Upgrade header.
  • 2XX: success status code
    • 200 OK: The request is successful and the desired response header or data body will be returned with the response
    • 201 Created:
    • 202 Accepted:
    • 203 Non – Authoritative Information:
    • 204 No Content:
    • 205 Reset the Content:
    • 206 Partial Content:
  • 3XX: redirection
    • 300 Multiple Choices:
    • 301 version Permanently:
    • 302 Found:
    • 303 See Other:
    • 304 Not Modified:
    • 305 Use Proxy:
    • Unused:
    • 307 Temporary Redirect:
  • 4XX: Client error
    • 400 Bad Request:
    • 401 Unauthorized:
    • 402 Payment Required:
    • 403 Forbidden:
    • 404 Not Found:
    • 405 Method Not Allowed:
    • 406 Not Acceptable:
    • 407 Proxy Authentication Required:
    • 408 Request Timeout:
    • 409 Conflict:
    • 410 Gone:
    • 411 Length Required:
    • 412 Precondition Failed:
    • 413 Request Entity Too Large:
    • 414 Request-URI Too Long:
    • 415 Unsupported Media Type:
    • 416 Requested Range Not Satisfiable:
    • 417 Expectation Failed:
  • 5XX: Server error
    • 500 Internal Server Error:
    • 501 Not Implemented:
    • 502 Bad Gateway:
    • 503 Service Unavailable:
    • 504 Gateway Timeout:
    • 505 HTTP Version Not Supported:

$CSS part

What are the CSS selectors

  1. * Universal selector: select all elements, do not participate in the calculation of priority, compatibility IE6+
  2. #X ID selector: select the element whose ID value is X, compatibility: IE6+
  3. .x class selector: select elements in class that contain X, compatibility: IE6+
  4. X Y descendant selectors: select elements that satisfy Y selectors in descendant nodes that satisfy X selector. Compatibility: IE6+
  5. X element selector: select all elements marked X, compatibility: IE6+
  6. : Link, : visited, : focus, : hover, : active Link state: select specific state of link elements, order LoVe HAte, compatibility: IE4+
  7. X + Y direct sibling selector: selects the element satisfying the Y selector in the first sibling node after X, compatibility: IE7+
  8. X > Y child selector: Selects the element of the child element of X that satisfies the Y selector, compatibility: IE7+
  9. X to Y siblings: select elements that satisfy Y selectors in all sibling nodes after X. Compatibility: IE7+
  10. [attr] : selects all elements with the attr attribute set, compatible with IE7+
  11. [attr=value] : selects the element whose attribute value is exactly value
  12. [attr~=value] : Selects whitespace delimited attribute values, one of which happens to be an element of value
  13. [attr | = value] : choose attribute values for the value or the value – just the beginning of the element
  14. [attr^=value] : selects elements whose attribute values start with value
  15. [attr$=value] : Selects elements whose attribute value ends in value
  16. [attr=value]* : Selects the element whose attribute value contains value
  17. [:checked] : Select a single check box, check box, drop-down box to select the element in the state, compatibility: IE9+
  18. X:after, X::after :after pseudo-element, select the element’s virtual child element (the last child element of the element), in CSS3 :: represents the pseudo-element. Compatibility: After indicates Internet Explorer 8+. :: After indicates Internet Explorer 9+
  19. :hover: mouse over state elements, compatibility a tag IE4+, all elements IE7+
  20. :not(selector) : Selects elements that do not match selector. Does not participate in computing priority, compatibility: IE9+
  21. ::first-letter: pseudo-element, selects the first letter of the first line of the block element, compatible with IE5.5+
  22. ::first-line: pseudo-element, select the first line of the block element, compatible with IE5.5+
  23. :nth-child(an + b) : pseudo-class, select the element with an + b – 1 sibling node, where n >= 0, compatible IE9+
  24. :nth-last-child(an + b) : pseudo-class, select element with an + b – 1 sibling node where n >= 0, compatible IE9+
  25. X: nTH-of-type (an+b) : pseudo-class, X is the selector, parse to get the element label, select the element with an+b – 1 siblings of the same label. Compatibility with ie 9 +
  26. X: nTH-last-type (an+b) : pseudo-class, X is the selector, parse to get the element label, select the element followed by an+b-1 sibling nodes of the same label. Compatibility with ie 9 +
  27. X:first-child: pseudo-class that selects an element that satisfies the X selector and is the first child of its parent. Compatibility IE7 +
  28. X: last-Child: pseudo-class that selects an element that satisfies the X selector and is the last child of its parent. Compatibility with ie 9 +
  29. X:only-child: pseudo-class that selects an element that satisfies the X selector and is the only child of its parent. Compatibility with ie 9 +
  30. X:only of type: pseudo-class, selects the element selected by X, parses the element label, and selects it if it does not have sibling nodes of the same type. Compatibility with ie 9 +
  31. X:first-of-type: pseudo-class that selects the element selected by X and parses the element label if the element is the first sibling of an element of this type. Select it. Compatibility with ie 9 +

What is CSS Sprite, and what are its pros and cons

Concept: Splice multiple small images into one image. Adjust the background pattern to be displayed by background-position and element size.

Advantages:

  1. Reduce the number of HTTP requests, greatly improving page loading speed
  2. Increase image information repetition, improve compression ratio, reduce image size
  3. It is easy to change styles by changing colors or styles on one or several pictures

Disadvantages:

  1. Image merge trouble
  2. Maintenance trouble, modifying a picture may require a new layout of the entire picture, style

display: none;withvisibility: hidden;The difference between

Connection: They both make elements invisible

The difference between:

  1. display:none; Renders elements completely out of the render tree, taking up no space while rendering. visibility: hidden; The renderer element continues to occupy space, but the content is not visible
  2. display: none; Due to the disappearance of elements from the rendering tree, the descendant node attribute cannot be displayed by modifying the descendant node attribute. visibility: hidden; The descendant node disappears because it inherits the hidden, by setting visibility: visible; You can make descendant nodes explicit
  3. Changing the display of elements in a regular stream usually results in document rearrangements. Modifying the visibility attribute only causes the element to be redrawn.
  4. The screen reader will not read display: None; Element content; Will read visibility: hidden; Element content

CSS hack principle and common hack

Principle: Take advantage of CSS support in different browsers and parse results differently to write browser-specific styles. Common hacks are 1) attribute hacks. 2) Selector hack. 3) IE conditional notes

  • Note: Applicable to [IE5, IE9] The common formats are as follows
<! --[if IE 6]> Special instructions for IE 6 here <! [endif]-->Copy the code
  • Selector hack: Different browsers support different selectors
/***** Selector Hacks ******/ /* IE6 and below */ * html #uno { color: red } /* IE7 */ *:first-child+html #dos { color: red } /* IE7, FF, Saf, Opera */ html>body #tres { color: Red} /* IE8, FF, Opera (Everything but IE 6,7) */ HTML >/**/body #cuatro {color: Red} /* Opera 9.27 and below, Safari 2 */ HTML :first-child #cinco {color: red } /* Safari 2-3 */ html[xmlns*=""] body:last-child #seis { color: Red} /* Safari 3+, Chrome 1+, opera9+, ff 3.5+ */ body:nth-of-type(1) #siete {color: Red} /* Safari 3+, chrome 1+, opera9+, ff 3.5+ */ body:first-of type #ocho {color: red } /* saf3+, chrome1+ */ @media screen and (-webkit-min-device-pixel-ratio:0) { #diez { color: red } } /* iPhone / mobile webkit */ @media screen and (max-device-width: 480px) { #veintiseis { color: Red}} /* Safari 2-3.1 */ HTML [XMLNS *=""]:root #trece {color: 2-3.1 - red} / * Safari, Opera 9.25 * / * | HTML/XMLNS * = "" # catorce {color: red } /* Everything but IE6-8 */ :root *> #quince { color: red } /* IE7 */ *+html #dieciocho { color: red } /* Firefox only. 1+ */ #veinticuatro, x:-moz-any-link { color: Red} /* Firefox 3.0+ */ #veinticinco, x:-moz-any-link, x:default {color: red}Copy the code
  • Attribute hacks: Different browser resolution bugs or methods
/* IE6 */ #once { _color: blue } /* IE6, IE7 */ #doce { *color: blue; /* or #color: blue */ } /* Everything but IE6 */ #diecisiete { color/**/: blue } /* IE6, IE7, IE8 */ #diecinueve { color: blue\9; } /* IE7, IE8 */ #veinte { color/*\**/: blue\9; } /* IE6, IE7 -- acts as an ! important */ #veintesiete { color: blue ! ie; } /* string after ! can be anything */Copy the code

Specified Value,computed Value, and used value methods

  • Specified value: Shall be calculated as follows:

    1. If the stylesheet sets a value, use that value
    2. If no value is set, the property is an inherited property, inherited from the parent element
    3. If not, and not an inherited property, use the initial value specified by the CSS specification
  • Computed Value: Specified Value is computed according to the behavior defined by the specification, usually the relative value is calculated as the absolute value, for example, EM is computed according to font size. Properties that use percentages and require a layout to determine the final value, such as width, margin. So the percent is directly computed value. The unitless value of line-height is also used directly as computed value. These values will get the absolute value when calculating the Used value. The main use of computed Value is for inheritance

  • Used Value: The final calculated value of an attribute. For most attributes, this can be obtained using window.getComputedstyle. The size value is in pixels. The following properties depend on the layout,

    • background-position
    • bottom, left, right, top
    • height, width
    • margin-bottom, margin-left, margin-right, margin-top
    • min-height, min-width
    • padding-bottom, padding-left, padding-right, padding-top
    • text-indent

linkwith@importThe difference between

  1. linkIt’s HTML,@importIs the CSS style
  2. linkMaximum support for parallel downloads,@importExcessive nesting causes serial downloads to occurFOUC
  3. linkCan be achieved byrel="alternate stylesheet"Specifying candidate styles
  4. The browser tolinkSupport earlier than@import, you can use@importHide styles from older browsers
  5. @importYou can reference other files in the CSS file before the style rule
  6. Overall: Link is better than @import

display: block;anddisplay: inline;The difference between

Block element features:

1. In normal flow, if width is not set, parent container 2 is automatically filled. Margin /padding 3 can be applied. If the height is not set, the height will be extended to include the children of the regular stream. Layout in regular flow between the position of the elements before and after (exclusive horizontal space) 5. Ignore the vertical – align

Features of inline elements

1. Horizontal layout based on direction 2. No line breaks before and after elements 3. Margin /padding does not apply to vertical elements, but horizontal ones. 5. Width /height attributes do not apply to non-replacement inline elements. Not replace inline elements of high line box be determined by the line – height, replace the inline elements line box by height, high margin, padding, border decided to 6. The float or absolute position is converted to block 7. The vertical-align attribute takes effect

PNG,GIF,JPG difference and how to choose

Resources: Select the correct image format GIF:

  1. 8 bit pixels, 256 colors
  2. Lossless compression
  3. Support for simple animations
  4. Support Boolean transparency
  5. Suitable for simple animation

JPEG:

  1. Color limited to 256
  2. Lossy compression
  3. Compression quality can be controlled
  4. Transparency not supported
  5. Suitable for photos

PNG:

  1. There is PNG8 and Truecolor PNG
  2. PNG8 similar to GIF color cap of 256, small file, support alpha transparency, no animation
  3. Suitable for ICONS, backgrounds, buttons

What are the inherited properties of the CSS

What are the common bugs, defects, or standard inconsistencies in IE6? How to solve them

  • IE6 does not support min-height.
.target { min-height: 100px; height: auto ! important; height: 100px; // The content height in IE6 exceeds the automatic extension height}Copy the code
  • The serial numbers of Li in OL are all 1 without increasing. Display: list-item;

  • Unlocated parent element Overflow: auto; , including position: relative; Child element, overflow when child element is higher than parent element. 1) Remove the child element position: relative; 2) When the child element cannot be removed, the parent element position: relative;

<style type="text/css">
.outer {
    width: 215px;
    height: 100px;
    border: 1px solid red;
    overflow: auto;
    position: relative;  /* 修复bug */
}
.inner {
    width: 100px;
    height: 200px;
    background-color: purple;
    position: relative;
}
</style>

<div class="outer">
    <div class="inner"></div>
</div>
Copy the code
  • IE6 support onlyaOf the label:hoverUse js to listen for mouseEnter, mouseleave events for elements, add class implementation effect:
<style type="text/css">
.p:hover,
.hover {
    background: purple;
}
</style>

<p class="p" id="target">aaaa bbbbb<span>DDDDDDDDDDDd</span> aaaa lkjlkjdf j</p>

<script type="text/javascript">
function addClass(elem, cls) {
    if (elem.className) {
        elem.className += ' ' + cls;
    } else {
        elem.className = cls;
    }
}
function removeClass(elem, cls) {
    var className = ' ' + elem.className + ' ';
    var reg = new RegExp(' +' + cls + ' +', 'g');
    elem.className = className.replace(reg, ' ').replace(/^ +| +$/, '');
}

var target = document.getElementById('target');
if (target.attachEvent) {
    target.attachEvent('onmouseenter', function () {
        addClass(target, 'hover');
    });
    target.attachEvent('onmouseleave', function () {
        removeClass(target, 'hover');
    })
}
</script>
Copy the code
  • IE5-8 is not supportedopacity, solutions:
.opacity {opacity: 0.4 filter: alpha(opacity=60); /* for IE5-7 */ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)"; /* for IE 8*/ }Copy the code
  • IE6 in setting upheightLess thanfont-sizeIs the height value offont-size, solutions:font-size: 0;
  • Internet Explorer 6 does not support PNG transparent backgrounds. Solution: Use GIF images in Internet Explorer 6
  • 6-7 is not supporteddisplay: inline-blockWorkaround: Set inline and trigger hasLayout
    display: inline-block;
    *display: inline;
    *zoom: 1;
Copy the code
  • In IE6, the margin of a floating element that touches the parent element boundary in the floating direction is doubled. Solution: 1) Use padding to control spacing. 2) Floating elementsdisplay: inline;This solves the problem without any side effects: the CSS standard states that the floating element display:inline automatically adjusts to a block
  • IE6 cannot achieve horizontal center by setting the width and left and right margins to auto for block-level elementstext-align: center;

How do I clean up floating elements when a container contains several floating elements

  1. Add additional elements and set before the container element closes the tagclear: both
  2. The parent element triggers the block-level formatting context (see the block-level Visual Context section)
  3. Set container element pseudo-element cleanup recommended cleanup float method
/** * Use * 1 content with Spaces in standard browsers to fix white space around floating elements in opera documents when * contenteditable properties appear * 2 Use display to use table instead of block: Can prevent container and * child element top-margin folding, this can make the cleaning effect with BFC, IE6/7 * zoom: 1; **/. Clearfix :before,. Clearfix :after {content: ""; /* 1 */ display: table; /* 2 */ } .clearfix:after { clear: both; } /** * IE 6/7 use * to trigger hasLayout to implement including float **/. Clearfix {*zoom: 1; }Copy the code

What is a FOUC? How to avoid

Flash Of Unstyled Content: The browser displays the document in the default style before the user-defined style sheet is loaded, and redisplays the document after the user style is loaded and rendered, causing the page to blink. Solution: Put the stylesheet in the head of the document

How to create block formatting contexts and what is the use of BFC

Create a rule:

  1. The root element
  2. Float element (floatnotnone)
  3. Absolute positioning element (positionValues forabsoluteorfixed)
  4. displayValues forinline-block.table-cell.table-caption.flex.inline-flexOne of the elements
  5. overflownotvisibleThe elements of the

Function:

  1. You can include floating elements
  2. Not overridden by floating elements
  3. Prevents margin folding of parent and child elements

The display, float, the relationship between the position

  1. ifdisplayNone, then neither position nor float is in effect, in which case the element produces no box
  2. Otherwise, if position is absolute or fixed, the box is absolutely positioned, float evaluates to None, and display is adjusted according to the table below.
  3. Otherwise, if float is not None, the box is floating and display is adjusted according to the table below
  4. Otherwise, if the element is the root, display adjusts according to the following table
  5. In other cases display values are specified to sum up: absolute positioning, floating, root elements all need to adjust display

Collapsing margins

Two or more adjacent margins are merged into one margin, called margin folding. Here are the rules:

  1. Vertical margins of block elements in two or more adjacent normal flows collapse
  2. Margin of floating element /inline-block element/absolutely positioned element does not fold with margin of other elements in vertical direction
  3. An element that creates a block-level formatting context does not margin fold with its children
  4. The element’s own margin-bottom and margin-top folds when adjacent

How to determine the containing block of an element

  1. The contain block of the root element is called the initial contain block. It is anchored at the canvas Origin and has the same size as the viewPort in the continuous media. For Paged Media, its size is equal to page Area. The direction attribute of the initial containing block is the same as that of the root element.

  2. An element whose position is relative or static and whose contain block consists of the contents box of the ancestor element of the nearest block level (display: block,list-item, table)

  3. If the element position is fixed. For continuous media, its contain block is viewPort; For Paged Media, the contained block is page Area

  4. If position is absolute, its containing block is generated by the ancestor element whose most recent position is relative,absolute, or fixed, as follows:

    • If the ancestor element is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.
    • In other cases the include block consists of the padding edge of the ancestor node

    If the located ancestor element is not found, the contain block is the original contain block

Stacking context, layout rules

The default cascading order on the Z-axis is as follows (bottom to top) :

  1. The boundary and background of the root element
  2. The elements in a regular flow are in HTML order
  3. Floating block
  4. The positioned elements appear in the sequence in THE HTML

How to create stacking Context:

  1. The root element
  2. Z-index is not the positioning element of auto
  3. a flex item with a z-index value other than ‘auto’
  4. Opacity: element less than 1
  5. On mobile webkit and chrome22+, z-index to auto, position: fixed will also create a new stacking context

How to center an element horizontally

  • If I want the middle element to beInline elements in a regular stream, set for the parent elementtext-align: center;Can be realized
  • If I want the middle element to beBlock elements in a regular stream, 1) Set the width for the element, and 2) set the left and right margin to Auto. 3) In IE6, it needs to be set on the parent elementtext-align: center;And restores the required value to the child element
<body>
    <div class="content">
    aaaaaa aaaaaa a a a a a a a a
    </div>
</body>

<style>
    body {
        background: #DDD;
        text-align: center; /* 3 */
    }
    .content {
        width: 500px;      /* 1 */
        text-align: left;  /* 3 */
        margin: 0 auto;    /* 2 */

        background: purple;
    }
</style>
Copy the code
  • If I want the middle element to beThe floating element, 1) Set the width for the element, 2)position: relative;3) The floating offset (left or right) is set to 50%. 4) The floating margin is set to half the element width multiplied by -1
<body>
    <div class="content">
    aaaaaa aaaaaa a a a a a a a a
    </div>
</body>

<style>
    body {
        background: #DDD;
    }
    .content {
        width: 500px;         /* 1 */
        float: left;

        position: relative;   /* 2 */
        left: 50%;            /* 3 */
        margin-left: -250px;  /* 4 */

        background-color: purple;
    }
</style>
Copy the code
  • If you want the center element to be absolutely positioned, 1) set the width of the element, 2) set the offset to 50%, and 3) set the offset margin to half the element width multiplied by -1
<body>
    <div class="content">
    aaaaaa aaaaaa a a a a a a a a
    </div>
</body>

<style>
    body {
        background: #DDD;
        position: relative;
    }
    .content {
        width: 800px;

        position: absolute;
        left: 50%;
        margin-left: -400px;

        background-color: purple;
    }
</style>
Copy the code
  • If you want the center element to be absolutely positioned, 1) set the width for the element, 2) set the left and right offsets to 0, and 3) set the left and right margins to Auto
<body>
    <div class="content">
    aaaaaa aaaaaa a a a a a a a a
    </div>
</body>

<style>
    body {
        background: #DDD;
        position: relative;
    }
    .content {
        width: 800px;

        position: absolute;
        margin: 0 auto;
        left: 0;
        right: 0;

        background-color: purple;
    }
</style>
Copy the code

How do I center an element vertically

Read: 6 Methods For Vertical Phoebe With CSS. Eight types of CSS are vertically centered

  • The element that needs to be centered isSingle-line text, sets greater than for the element that contains textfont-sizetheline-height:
<p class="text">center text</p>

<style>
.text {
    line-height: 200px;
}
</style>
Copy the code

$javascript concept section

What is the difference between E.tropName and E.lldb (propName) for DOM element E

  • LLDB etAttribute(), which is a standard DOM method for manipulating the attributes of document elements. It can be used in any document and returns the attributes of the elements set in the source file
  • E. plompName is usually used to access the properties of a specific element in an HTML document. After the browser parses the elements, the corresponding objects are generated (for example, HTMLAnchorElement is generated by a tag). The properties of these objects are obtained according to specific rules and attribute Settings. Access can only be done using getAttribute
  • LLDB etAttribute() return value set in source file, type string or null (LLDB)
  • The return value of e.propName may be a string, Boolean, object, undefined, and so on
  • Most attributes have a one-to-one relationship with property. Modifying one will affect the other attributes, such as ID and title
  • Some Boolean properties<input hidden/>HasAttribute and removeAttribute, or the corresponding property
  • like<a href=".. /index.html">link</a>Href property, you need to get the full URL by converting it to a property
  • Some attributes and properties do not correspond one to one, for example, in the form control<input value="hello"/>The corresponding value is defaultValue. Modifying or setting the value property changes the current value of the control. SetAttribute modifying the value property does not change the value property

OffsetWidth/offsetHeight, clientWidth/clientHeight scrollWidth/scrollHeight difference

  • The return value offsetWidth/offsetHeight contains content + padding + border, which has the same effect as LLDB etBoundingClientRect()
  • The clientWidth/clientHeight return value contains only content + padding and no scroll bar, if any
  • ScrollWidth /scrollHeight Return value contains content + padding + size of overflow content

Measuring Element Dimension and Location with CSSOM in Windows Internet Explorer 9

XMLHttpRequest Generic properties and methods

  1. readyState: Integer indicating the request status. The value can be:
  • UNSENT (0) : Object created
  • OPENED (1) : OPENED () is called successfully. In this state, you can set the request header for XHR, or send() to send the request
  • HEADERS_RECEIVED(2) : All redirects have completed access automatically, and the HTTP header for the final response has been received
  • LOADING(3) : The response body is receiving
  • DONE(4) : Data transmission is complete or an error occurs during transmission
  1. onreadystatechange: function called when readyState changes
  2. status: HTTP status code returned by the server (e.g., 200, 404)
  3. statusText: HTTP status information returned by the server (e.g., OK, No Content)
  4. responseText: the complete response from the server as a string
  5. responseXMLThe: Document object represents the XML Document parsed into the server’s response
  6. abort(): Cancels the asynchronous HTTP request
  7. getAllResponseHeaders(): Returns a string containing all HTTP headers sent by the server in the response. Each header is a colon-delimited name/value pair, and a carriage return/newline is used to separate the header lines
  8. getResponseHeader(headerName): Returns the header value corresponding to headName
  9. open(method, url, asynchronous [, user, password]): initializes the request to be sent to the server. Method is a case insensitive HTTP method. A URL is a relative or absolute URL to which the request is sent; Asynchronous indicates whether the request is asynchronous. User and password provide authentication
  10. setRequestHeader(name, value): Sets the HTTP header
  11. send(body): Initializes the server request. The body argument contains the body of the request, which is a key-value pair string for the POST request; For GET requests, null

Differences and connections between Focus /blur and focusin/focusout

  1. Focus /blur does not bubble, focusin/focusout bubbles
  2. Focus/Blur has good compatibility, focusin/ FocusOut maintains good compatibility in all browsers except FireFox. If event hosting is required, Consider using event capture elem. AddEventListener (‘focus’, handler, true) in FireFox
  3. Elements that can gain focus:
    1. window
    2. Links are clicked or keyboard operated
    3. The form space is clicked or keyboard manipulated
    4. Set up thetabindexProperty of the element to be clicked or keyboard operated on

Mouseover /mouseout/MouseEnter /mouseleave

  1. Mouseover /mouseout is a standard event supported by all browsers; Mouseenter/Mouseleave is a unique event introduced by Internet Explorer 5.5 and later adopted by the DOM3 standard and supported by modern standard browsers
  2. Mouseover /mouseout are bubbling events; Mouseenter /mouseleave does not bubble. Mouseover/Mouseout hosting is recommended to improve performance when you need to listen for mouseover/mouseout events for multiple elements
  3. In the standard event model, event.target represents the element moved in/out,vent. RelatedTarget corresponds to the element moved out/such. In old IE, event.srcElement represented the element that was moved in/out, event.toElement represented the target element that was moved out, and event.fromElement represented the source element that was moved in

Example: when the mouse moves out of the div#target element, the logic is as follows:

<div id="target"><span>test</span></div> <script type="text/javascript"> var target = document.getElementById('target');  if (target.addEventListener) { target.addEventListener('mouseout', mouseoutHandler, false); } else if (target.attachEvent) { target.attachEvent('onmouseout', mouseoutHandler); } function mouseoutHandler(e) { e = e || window.event; var target = e.target || e.srcElement; If (target.id! == 'target') { return; } / / mouse is removed from the element or move to child elements var relatedTarget = event. The relatedTarget | | e. oElement; while (relatedTarget ! == target && relatedTarget.nodeName.toUpperCase() ! == 'BODY') { relatedTarget = relatedTarget.parentNode; } // If (relatedTarget === target) {return; } // do what you need to do //alert(' mouse out '); } </script>Copy the code

SessionStorage and localStorage, cookies

  1. They’re all saved in the browser, they have size limits, they have origin limits
  2. Cookie will be sent to the server when the request, as a session identifier, the server can modify the cookie; Web Storage does not send to the server
  3. Cookies have the concept of path. The child path can access the parent path cookie, but the parent path cannot access the child path cookie
  4. Validity period: The cookie is valid within the set validity period. By default, the browser is closed. SessionStorage is valid until the window closes, and localStorage is valid until the user is deleted
  5. Shared: sessionStorage cannot be shared. LocalStorage is shared between same-origin documents. Cookies are shared between same-origin documents that comply with the PATH rule
  6. Changes to localStorage trigger update events in other document Windows
  7. Cookies have the secure property requiring HTTPS transmission
  8. A browser cannot store more than 300 cookies, a single server cannot store more than 20 cookies, and each cookie cannot exceed 4K. The size of web storage can reach 5M

Javascript communicates across domains

Same-origin: The same origin of two documents must be met

  1. The agreement is the same
  2. Domain name is the same
  3. The same port

Cross-domain communication: If the target and the current window do not meet the same origin condition when JS performs DOM operation and communication, the browser prevents cross-domain operation for security. Cross-domain communication usually has the following methods

  • If it’s log or something simpleOne-way communication, the newly built<img>.<script>.<link>.<iframe>Element, set to the target URL via the SRC, href attribute. Implement cross-domain requests
  • If the request isThe json data, the use of<script>Make a JSONP request
  • Multi-window communication in modern browsers uses the HTML5 specification targetWindow. PostMessage (data, origin); Where data is the object to be sent and Origin is the origin of the target window. window.addEventListener(‘message’, handler, false); Handler’s Event. data is the data sent by postMessage, event.origin is the origin of the sending window, and event.source is the reference to the sending window
  • The internal server agent requests the cross-domain URL and returns the data
  • To request data across domains, modern browsers can use the CORS feature of the HTML5 specification, as long as the target server returns the HTTP header **Access-Control-Allow-Origin: *** can access cross-domain resources just like normal Ajax

How many data types do javascript have

Six basic data types

  • undefined
  • null
  • string
  • boolean
  • number
  • symbol(ES6)

A reference type

  • Object

What closure? What’s a closure for

A closure is a function defined in a scope that has access to all variables in that scope. The closure scope chain usually consists of three parts:

  1. Function scope itself.
  2. Scope when a closure is defined.
  3. Global scope.

Common uses for closures:

  1. Create privileged methods for access control
  2. Event handlers and callbacks

How many ways does javascript define functions

  1. Function declaration expression
  2. The function operator
  3. Function constructor
  4. ES6:arrow function

MDN:Functions_and_function_scope

Application storage and offline Web applications

HTML5’s new application cache allows Web applications to save the application itself to the user’s browser, which can be accessed offline. < HTML manifest=” myapp.appCache “> < HTML manifest=” myapp.appCache “> < HTML manifest=” myapp.appCache “> 2. The first line of the manifest file is the CACHE manifest, and the rest is a list of urls to CACHE. Each line is relative to the URL of the manifest file. 3. Urls are classified into three types: CACHE: The default type. NETWORK: indicates that resources are never cached. FALLBACK: Each line contains two urls. The second URL refers to the resource that needs to be loaded and stored in the cache. The first URL is a prefix. Any URL that matches this prefix is not cached, and if it fails to load such a URL from the network, it is replaced with the cached resource specified by the second URL. Here is an example file:

CACHE MANIFEST

CACHE:
myapp.html
myapp.css
myapp.js

FALLBACK:
videos/ offline_help.html

NETWORK:
cgi/
Copy the code

The client stores localStorage and sessionStorage

  • LocalStorage is valid forever, sessionStorage is valid until the top-level window closes
  • SessionStorage allows access only to documents in the same window, such as same-origin documents introduced through iframe.
  • Storage objects are usually used as normal javascript objects: String values can be accessed by setting properties, setItem(key, value), getItem(key) to read, removeItem(key) to delete, clear() to delete all data, length to indicate the number of stored data items, Key (index) Returns the key of the corresponding index
localStorage.setItem('x', 1); // storge x->1 localStorage.getItem('x); For (var I = 0, len = localstorage.length; i < len; ++i ) { var name = localStorage.key(i); var value = localStorage.getItem(name); } localStorage.removeItem('x'); // remove x localStorage.clear(); // remove all dataCopy the code

Cookies and their operations

  • Cookies are a small amount of data stored by web browsers. They were originally designed for server use as an extension of the HTTP protocol. Cookie data is automatically transferred between the browser and the server.
  • Check for support by reading and writing cookies
  • Cookie attributes name, value, max-age, path, domain, secure;
  • The default cookie validity period is the browser session. Once the user closes the browser, the data is lost. You can set the max-age=seconds attribute to tell the browser the cookie validity period
  • Cookie scope is determined by document source and document path, and is configured by path and domain so that web pages are accessible to documents in the same directory or subdirectory
  • The method of saving data through cookies is: set a string for document.cookie that matches the target as follows
  • Read document.cookie get ‘; ‘delimited string, key=value, parsed to get the result
document.cookie = 'name=qiu; max-age=9999; path=/; domain=domain; secure'; document.cookie = 'name=aaa; path=/; domain=domain; secure'; // To change the value of the cookie, use the same name, path, and field, the new value // to set the cookie, the same method can be used to change the validity period // set max-age to 0 can delete the specified cookie // read the cookie, Cookie returns a string of key-value pairs, // 'between different key-value pairs; 'separation. Get the desired value by parsingCopy the code

Cookieutil.js: a self-written cookie manipulation tool

What methods does javascript have to define objects

  1. Object literals:var obj = {};
  2. Constructor:var obj = new Object();
  3. Object.create(): var obj = Object.create(Object.prototype);

How does the === operator determine equality

  1. If two values are not of the same type, they are not equal
  2. If both values are null or undefined, they are equal
  3. If both values are Boolean true or false, they are equal
  4. If one of them is a NaN, they are not equal
  5. If they’re both numerical and they’re equal, they’re equal. Minus 0 is equal to 0
  6. If they are both strings and contain the same 16-bit value in the same place, they are equal; If they are unequal in length or content, they are not equal; Both strings show the same result but are encoded differently. == and === are considered unequal
  7. If they refer to the same object, array, or function, they are equal; If they point to different objects, they are not equal

What is the flow of the == operator to determine equality

  1. If the two values are of the same type, compare them using the === comparison method
  2. If the types are different, use the following rules for comparison
  3. If one of the values is null and the other is undefined, they are equal
  4. If one value is a number and the other is a string, convert the string to a number for comparison
  5. If there is a Boolean type, convert true to 1 and false to 0, and continue the comparison using the == rule
  6. If one value is an object and the other is a number or string, convert the object to its original value and continue the comparison using the == rule
  7. All other cases are considered unequal

Object to string conversion steps

  1. If the object has a toString() method, javascript calls it. If a primitive value (e.g., Primitive Value: String Number Boolean) is returned, convert the value to a string as a result
  2. If the object has no toString() method or the return value is not the original value, javascript looks for the object’s valueOf() method, calls it if it exists, and returns the original value as a string as the result
  3. Otherwise, javascript cannot get a raw value from toString() or valueOf(), throws a TypeError

Object to number conversion steps

1. If the object has a valueOf() method and returns the element value, javascript converts the returned value to a number as the result 2. Otherwise, if the object has toString() and returns the original value, javascript converts the returned result to a number as the result 3. Otherwise, throws a TypeErrorCopy the code

<,>,<=,>= comparison rules

All comparison operators support arbitrary types, but comparisons only support numbers and strings, so you need to perform the necessary conversions and then compare, as follows:

  1. If the operand is an object, convert to the original value: if the valueOf method returns the original value, use this value, otherwise use the result of the toString method, and an error is reported if the conversion fails
  2. After the necessary object-to-original conversion, if both operands are strings, compare them alphabetically (the size of their 16-bit Unicode values)
  3. Otherwise, if one of the operands is not a string, the two operands are converted to numbers for comparison

+ operator workflow

  1. If any of the operands are objects, convert to the original value
  2. If one of the operands is a string, all the other operands are converted to strings and concatenated
  3. Otherwise: All operands are converted to numbers and added

What are the properties of the arguments variable inside the function? How do I convert it to an array

  • Arguments A local variable included in all functions that is an array object corresponding to the arguments to the function call. The default object is overridden if the function defines an argument with the same name
  • Arguments [index] correspond to arguments at the time of the function call, and arguments modified by arguments are modified at the same time
  • Arguments. length is the number of arguments (function. length denotes the length of the parameter)
  • Arguments. callee is the function itself that is currently executing. Use this property to make recursive calls that need to be aware of changes to this
  • Arguments. caller is a function that calls the current function (discarded).
  • Convert to array:var args = Array.prototype.slice.call(arguments, 0);

What about the DOM event model and writing an EventUtil utility class for event management compatibility

  • A DOM event consists of two stages: capture and bubble. The capture stage event triggers the event from the window and then passes through the ancestor node to the DOM element that triggered the event once. Bubbling phase events are passed from the initial element to the ancestor node until the window
  • Standard event listeners elem. AddEventListener (type, the handler, the capture)/elem removeEventListener (type, the handler, the capture) : Handler receives the event object that holds the event information as a parameter, event.target is the object that triggers the event, handler calls context this is the object that binds the listener, event.preventDefault() canceles the event default, Event. StopPropagation ()/event. StopImmediatePropagation cancel events ()
  • Elem. AttachEvent (‘on’+type, handler)/elem. DetachEvent (‘on’+type, handler) : The handler does not receive an event as a parameter, the event information is stored in window.event, and the event object is event.srcElement. Handler execution context this for Window mimics the standard model by calling handler.call(elem, Event) in a closure and then returning the closure, ensuring listener removal. Cancels event default behavior when event.returnValue is false, and cancels time propagation when event.cancleBubble is true
  • Event bubbling is often used to host event handlers to improve program performance.
/** * Cross-browser event handling tool. Only bubbles are supported. Does not support capture * @ author ([email protected]) * / var EventUtil = {getEvent: function (event) {return event | | window. The event; }, getTarget: function (event) { return event.target || event.srcElement; }, // Return the listener successfully registered, IE needs to use the return value to remove listener on: function (elem, type, handler) { if (elem.addEventListener) { elem.addEventListener(type, handler, false); return handler; } else if (elem.attachEvent) { var wrapper = function () { var event = window.event; event.target = event.srcElement; handler.call(elem, event); }; elem.attachEvent('on' + type, wrapper); return wrapper; } }, off: function (elem, type, handler) { if (elem.removeEventListener) { elem.removeEventListener(type, handler, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, handler); } }, preventDefault: function (event) { if (event.preventDefault) { event.preventDefault(); } else if ('returnValue' in event) { event.returnValue = false; } }, stopPropagation: function (event) { if (event.stopPropagation) { event.stopPropagation(); } else if ('cancelBubble' in event) { event.cancelBubble = true; }}, /** * keypress events get input characters across browsers * some browsers also trigger keypress on some special keys, in which case null **/ getChar is returned: function (event) { if (event.which == null) { return String.fromCharCode(event.keyCode); // IE } else if (event.which ! = 0 && event.charCode ! = 0) { return String.fromCharCode(event.which); // the rest } else { return null; // special key } } };Copy the code

Evaluate the advantages and disadvantages of the three approaches to inheritance and make improvements

Function Shape() {} function Rect() {} prototype = new Shape(); // rect. prototype = shape. prototype; // rect. prototype = object.create (shape.prototype); Rect.prototype.area = function () { // do something };Copy the code

Method 1:

  1. Advantages: Correctly set up the prototype chain to achieve inheritance
  2. Advantages: The attributes of the parent instance are inherited, the prototype chain search efficiency is improved, and some attributes can be provided with reasonable default values
  3. Disadvantages: When the parent instance attribute is a reference type, improper modification will cause all subclasses to be modified
  4. Disadvantages: When creating an instance of a parent class as a prototype for a subclass, it may not be possible to determine the reasonable parameters required by the constructor. The arguments provided thus make no practical sense to pass to the subclass; they should be initialized and set in the constructor when the subclass needs them
  5. Conclusion: Inheritance should be inherited methods, not properties, and setting superclass instance properties for a subclass should be initialized by calling the superclass constructor in the subclass constructor

Method 2:

  1. Advantages: Correctly set up the prototype chain to achieve inheritance
  2. Disadvantages: The superclass constructor prototype is the same as the subclass. Modifying the subclass stereotype add method modifies the parent class

Method 3:

  1. Advantages: Set up the prototype chain correctly and avoid the disadvantages of Method 1.2
  2. Disadvantages: ES5 methods require compatibility

Improvement:

  1. All three methods should call the superclass constructor in the subclass constructor to initialize the instance properties
function Rect() {
    Shape.call(this);
}
Copy the code
  1. Replace the subclass default stereotype with a newly created object, setRect.prototype.constructor = Rect;Ensure consistency
  2. The third method of polyfill:
function create(obj) {
    if (Object.create) {
        return Object.create(obj);
    }

    function f() {};
    f.prototype = obj;
    return new f();
}
Copy the code

$javascript programming section

Please use native JS to implement a function to add a transparent mask (variable transparency, default 0.2) to any element of the page to make this area click invalid. It is required to be compatible with IE8+ and all major browsers. The mask layer effect is as shown below:

<style> #target { width: 200px; height: 300px; margin: 40px; background-color: tomato; } < / style > < div id = "target" > < / div > < script > function addMask (elem, opacity) {opacity = opacity | | 0.2; var rect = elem.getBoundingClientRect(); var style = getComputedStyle(elem, null); var mask = document.createElement('div'); mask.style.position = 'absolute'; var marginLeft = parseFloat(style.marginLeft); mask.style.left = (elem.offsetLeft - marginLeft) + 'px'; var marginTop = parseFloat(style.marginTop); mask.style.top = (elem.offsetTop - marginTop) + 'px'; mask.style.zIndex = 9999; mask.style.opacity = '' + opacity; mask.style.backgroundColor = '#000'; mask.style.width = (parseFloat(style.marginLeft) + parseFloat(style.marginRight) + rect.width) + 'px'; mask.style.height = (parseFloat(style.marginTop) + parseFloat(style.marginBottom) + rect.height) + 'px'; elem.parentNode.appendChild(mask); } var target = document.getElementById('target'); addMask(target); target.addEventListener('click', function () { console.log('click'); }, false); </script>Copy the code

Please write in code (today is Monday x) where x is the day of the week, if it is Monday, the output should be “Today is Monday”.

Var days = [' day ',' one ',' two ',' three ',' four ',' five ',' six ']; var date = new Date(); Console. log(' Today is Sunday '+ days[date.getday ()]);Copy the code

The following code wants to loop delay output 0, 1, 2, 3, 4. Is the output correct? If not, please explain why and modify the code inside the loop to output the correct result

for (var i = 0; i < 5; ++i) {
  setTimeout(function () {
    console.log(i + ' ');
  }, 100);
}
Copy the code

Cannot output the correct result because the argument function accepted by setTimeout in the loop accesses the variable I through the closure. The javascript running environment is single thread. The function registered by setTimeout needs to wait for the thread to be idle before it can be executed. At this point, the for loop has ended and the I value is 5. The five timed outputs are all 5 modifications: put setTimeout in the function immediate call expression, pass the I value as an argument to the wrapping function, and create a new closure

for (var i = 0; i < 5; ++i) {
  (function (i) {
    setTimeout(function () {
      console.log(i + ' ');
    }, 100);
  }(i));
}
Copy the code

You have a Page class whose prototype object has a number of methods (such as postMsg) that start with POST; Please design a function that will batch modify the original Page postXXX method, while preserving its original function, add interception validation for each postXXX method, when chekc returns true, continue to execute the original postXXX method. The original postXXX method is no longer executed when false is returned

function Page() {} Page.prototype = { constructor: Page, postA: function (a) { console.log('a:' + a); }, postB: function (b) { console.log('b:' + b); }, postC: function (c) { console.log('c:' + c); }, check: function () {return math.random () > 0.5; } } function checkfy(obj) { for (var key in obj) { if (key.indexOf('post') === 0 && typeof obj[key] === 'function') { (function (key) { var fn = obj[key]; obj[key] = function () { if (obj.check()) { fn.apply(obj, arguments); }}; }(key)); } } } // end checkfy() checkfy(Page.prototype); var obj = new Page(); obj.postA('checkfy'); obj.postB('checkfy'); obj.postC('checkfy');Copy the code

Complete the tool-tip below

Write javascript deepClone function deepClone

function deepClone(obj) { var _toString = Object.prototype.toString; // null, undefined, non-object, function if (! obj || typeof obj ! == 'object') { return obj; } // DOM Node if (obj.nodeType && 'cloneNode' in obj) { return obj.cloneNode(true); } // Date if (_toString.call(obj) === '[object Date]') { return new Date(obj.getTime()); } // RegExp if (_toString.call(obj) === '[object RegExp]') { var flags = []; if (obj.global) { flags.push('g'); } if (obj.multiline) { flags.push('m'); } if (obj.ignoreCase) { flags.push('i'); } return new RegExp(obj.source, flags.join('')); } var result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}; for (var key in obj ) { result[key] = deepClone(obj[key]); } return result; } function A() { this.a = a; } var a = { name: 'qiu', birth: new Date(), pattern: /qiu/gim, container: document.body, hobbys: ['book', new Date(), /aaa/gim, 111] }; var c = new A(); var b = deepClone(c); console.log(c.a === b.a); console.log(c, b);Copy the code

Add code to move Button1 behind Button2 after mouse click on Button1

<! doctype html> <html> <head> <meta charset="utf-8"> <title>TEst</title> </head> <body> <div> <input type="button" id ="button1" value="1" /> <input type="button" id ="button2" value="2" /> </div> <script type="text/javascript"> var btn1 = document.getElementById('button1'); var btn2 = document.getElementById('button2'); addListener(btn1, 'click', function (event) { btn1.parentNode.insertBefore(btn2, btn1); }); function addListener(elem, type, handler) { if (elem.addEventListener) { elem.addEventListener(type, handler, false); return handler; } else if (elem.attachEvent) { function wrapper() { var event = window.event; event.target = event.srcElement; handler.call(elem, event); } elem.attachEvent('on' + type, wrapper); return wrapper; } } </script> </body> </html>Copy the code

Web page to realize a calculation of how much time left in the year countdown program, requiring the webpage real-time dynamic display of “×× year left ×× days ×× hours ×× minutes ×× seconds”

<! doctype html> <html> <head> <meta charset="utf-8"> <title>TEst</title> </head> <body> <span id="target"></span> <script Type ="text/javascript"> // for simplicity. Function getTimeString() {var start = new Date(); var end = new Date(start.getFullYear() + 1, 0, 1); var elapse = Math.floor((end - start) / 1000); var seconds = elapse % 60 ; var minutes = Math.floor(elapse / 60) % 60; var hours = Math.floor(elapse / (60 * 60)) % 24; var days = Math.floor(elapse / (60 * 60 * 24)) % 30; var months = Math.floor(elapse / (60 * 60 * 24 * 30)) % 12; var years = Math.floor(elapse / (60 * 60 * 24 * 30 * 12)); Return start.getFullYear() + years + months + days + hours + hours + minutes + minutes + seconds + 'seconds'; } function domText(elem, text) { if (text == undefined) { if (elem.textContent) { return elem.textContent; } else if (elem.innerText) { return elem.innerText; } } else { if (elem.textContent) { elem.textContent = text; } else if (elem.innerText) { elem.innerText = text; } else { elem.innerHTML = text; } } } var target = document.getElementById('target'); setInterval(function () { domText(target, getTimeString()); }, 1000) </script> </body> </html>Copy the code

Completes a function that takes an array of integers or arrays and returns a flattened array

[1, [2, [[3, 4], 5], 6]] => [1, 2, 3, 4, 5, 6]

    var data =  [1, [2, [ [3, 4], 5], 6]];

    function flat(data, result) {
        var i, d, len;
        for (i = 0, len = data.length; i < len; ++i) {
            d = data[i];
            if (typeof d === 'number') {
                result.push(d);
            } else {
                flat(d, result);
            }
        }
    }

    var result = [];
    flat(data, result);

    console.log(result);
Copy the code

How do I determine if an object is an array

This parameter is valid if the browser supports array.isarray (). Otherwise, you need to perform necessary verification

@param {Object} arg is required to test whether an Object is an array * @return {Boolean} If an Object is an array, return true. Otherwise it returns false * / function isArray (arg) {if (typeof arg = = = 'object') {return object. The prototype. ToString. Call (arg) = = = '[object Array]'; } return false; }Copy the code

Please review the following event listener code and suggest improvements

if (window.addEventListener) {
  var addListener = function (el, type, listener, useCapture) {
    el.addEventListener(type, listener, useCapture);
  };
}
else if (document.all) {
  addListener = function (el, type, listener) {
    el.attachEvent('on' + type, function () {
      listener.apply(el);
    });
  };
}
Copy the code

Function: Browser function detection implements cross-browser DOM event binding

Advantages:

  1. The test code is run only once, depending on the browser to determine the binding method
  2. throughlistener.apply(el)Resolve the inconsistency between this and the standard in IE listener
  3. Simple functionality in case the browser doesn’t support it, capture functionality in standard browsers

Disadvantages:

  1. Document. all is not reliable as IE detection, should use if(el.attachevent)
  2. AddListener has a different API in different browsers
  3. listener.applyMake this conform to the standard but the listener cannot be removed
  4. The listener parameter event in IE is not resolved. Target problem

Improvement:

var addListener; if (window.addEventListener) { addListener = function (el, type, listener, useCapture) { el.addEventListener(type, listener, useCapture); return listener; }; } else if (window.attachevent) {addListener = function (el, type, listener) { target var wrapper = function () { var event = window.event; event.target = event.srcElement; listener.call(el, event); }; el.attachEvent('on' + type, wrapper); return wrapper; // Return the wrapper. The caller can save, after remove}; }Copy the code

How do YOU tell if an object is a function

/** * If the current runtime environment returns 'function' on the typeof a callable (e.g., regular expression) *, use the generic method. * * @param {Any} arg needs to check whether the object is a function * @return {Boolean} If the argument is a function, return true, Function isFunction(arg) {if (arg) {if (typeof (/. == 'function') { return typeof arg === 'function'; } else { return Object.prototype.toString.call(arg) === '[object Function]'; } } // end if return false; }Copy the code

Write a function that takes a QUERY String in the URL as an argument and returns a parsed Object. The Query String is coded using Application/X-www-form-urlencoded

** @param {string} query The query string to be parsed, starting with? / function parseQuery(query) {var result = {}; / function parseQuery(query) {var result = {}; // Return an empty object if (typeof Query! == 'string') { return result; } // Remove the possible beginning of the string? if (query.charAt(0) === '? ') { query = query.substring(1); } var pairs = query.split('&'); var pair; var key, value; var i, len; for (i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i].split('='); // Application /x-www-form-urlencoded decodeURIComponent(pair[0]).replace(/\+/g, "); // Application /x-www-form-urlencoded decodeURIComponent(pair[0]). value = decodeURIComponent(pair[1]).replace(/\+/g, ' '); // If it is a new key, add if (! (key in result)) { result[key] = value; Else if (isArray(result[key])) {result[key].push(value); Else {var arr = [result[key]]; arr.push(value); result[key] = arr; } // end if-else } // end for return result; } function isArray(arg) { if (arg && typeof arg === 'object') { return Object.prototype.toString.call(arg) === '[object Array]'; } return false; } /** console.log(parseQuery('sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8')); * /Copy the code

Parses a complete URL and returns Object containing the same field as window.location

/** * parses a URL and generates the fields contained in the window.location object * location: * {* href: 'contains the full URL ', * origin:' contains the content before the pathname ', * protocol: * password: 'password ', // host:' complete hostname ', * hostname: 'Host name, not including port' * port: 'port number ', * pathName:' path to access resource on server/beginning ', * search: 'query String,? Start ', * hash: } * * @param {string} url specifies the url to parse * @return {Object} Specifies the Object to parse */ function parseUrl(url) {  var result = {}; var keys = ['href', 'origin', 'protocol', 'host', 'hostname', 'port', 'pathname', 'search', 'hash']; var i, len; var regexp = /(([^:]+:)\/\/(([^:\/\?#]+)(:\d+)?) )/(\ [^? #] *)? (\? [^ #] *)? (#. *)? /; var match = regexp.exec(url); if (match) { for (i = keys.length - 1; i >= 0; --i) { result[keys[i]] = match[i] ? match[i] : ''; } } return result; }Copy the code

The completion function getViewportSize returns the viewport size of the specified window

/ * * * the viewport of the query window size, if you do not specify a window, query the current window size * * / function getViewportSize (w) {w = w | | window; If ('innerHeight' in w) {return {width: w.innerwidth, height: w.innerheight}; } var d = w.document; / / 8 and below IE browser in standard mode the if (document.com patMode = = = "CSS1Compat ') {return {width: d.d ocumentElement. ClientWidth, height: d.documentElement.clientHeight }; } return {width: d.body. ClientWidth, height: d.body. ClientHeight}; }Copy the code

The completion function getScrollOffset returns the window scroll bar offset

/** * gets the offset of the scrollbar in the specified window. @param {window} w Specifies the window in which the scrollbar offset is to be obtained. @return {Object} obj. X specifies the horizontal scrollbar offset,obj. Y specifies the vertical scrollbar offset function getScrollOffset(w) { w = w || window; // if (w.pagexoffset! = null) { return { x: w.pageXOffset, y: w.pageYOffset }; } // Older versions of IE access different elements according to compatibility var d = w.document; if (d.compatMode === 'CSS1Compat') { return { x: d.documentElement.scrollLeft, y: d.documentElement.scrollTop } } return { x: d.body.scrollLeft, y: d.body.scrollTop }; }Copy the code

You have a string, richText, which is richText that needs to be displayed on the page. There is a requirement to add a class called PIC to the p tag that contains only one IMG element. Please write code to implement. You can use jQuery or KISSY.

function richText(text) {
    var div = document.createElement('div');
    div.innerHTML = text;
    var p = div.getElementsByTagName('p');
    var i, len;

    for (i = 0, len = p.length; i < len; ++i) {
        if (p[i].getElementsByTagName('img').length === 1) {
            p[i].classList.add('pic');
        }
    }

    return div.innerHTML;
}
Copy the code

Implement an Event class. Objects that inherit from this class will have two methods: on,off,once, and Trigger

function Event() { if (! (this instanceof Event)) { return new Event(); } this._callbacks = {}; } Event.prototype.on = function (type, handler) { this_callbacks = this._callbacks || {}; this._callbacks[type] = this.callbacks[type] || []; this._callbacks[type].push(handler); return this; }; Event.prototype.off = function (type, handler) { var list = this._callbacks[type]; if (list) { for (var i = list.length; i >= 0; --i) { if (list[i] === handler) { list.splice(i, 1); } } } return this; }; Event.prototype.trigger = function (type, data) { var list = this._callbacks[type]; if (list) { for (var i = 0, len = list.length; i < len; ++i) { list[i].call(this, data); }}}; Event.prototype.once = function (type, handler) { var self = this; function wrapper() { handler.apply(self, arguments); self.off(type, wrapper); } this.on(type, wrapper); return this; };Copy the code

Write a function to reverse the order of the list’s children

<ul id="target"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <script> var target = document.getElementById('target'); var i; var frag = document.createDocumentFragment(); for (i = target.children.length - 1; i &gt; = 0; --i) { frag.appendChild(target.children[i]); } target.appendChild(frag); </script>Copy the code

What does the following function do? What should be filled in the blank area

// define (function (window) { function fn(str) { this.str = str; } fn.prototype.format = function () { var arg = __1__; return this.str.replace(__2__, function (a, b) { return arg[b] || ''; }); }; window.fn = fn; })(window); // use (function () { var t = new fn('<p><a href="{0}">{1}</a><span>{2}</span></p>'); console.log(t.format('http://www.alibaba.com', 'Alibaba', 'Welcome')); }) ();Copy the code

The define section defines a simple template class, using {} as an escape tag, the number in the middle to indicate the replacement target, and the format argument to replace the template tag line with:

  1. Array.prototype.slice.call(arguments, 0)
  2. /\{\s*(\d+)\s*\}/g

Write a function to serialize a form (that is, serialize the key values in a form into a committable string)

<form id="target"> <select name="age"> <option value="aaa">aaa</option> <option value="bbb" selected>bbb</option> </select> <select name="friends" multiple> <option value="qiu" selected>qiu</option> <option value="de">de</option> <option value="qing" selected>qing</option> </select> <input name="name" value="qiudeqing"> <input type="password" name="password" value="11111"> <input type="hidden" name="salery" value="3333"> <textarea name="description">description</textarea> <input type="checkbox" name="hobby" checked value="football">Football <input type="checkbox" name="hobby" value="basketball">Basketball <input type="radio" name="sex" checked value="Female">Female <input type="radio" name="sex" value="Male">Male </form> <script> /** * Serializes a form element into a committable string ** @param {FormElement} form */ function serializeForm(form) {if (! form || form.nodeName.toUpperCase() ! == 'FORM') { return; } var result = []; var i, len; var field, fieldName, fieldType; for (i = 0, len = form.length; i < len; ++i) { field = form.elements[i]; fieldName = field.name; fieldType = field.type; if (field.disabled || ! fieldName) { continue; } // enf if switch (fieldType) { case 'text': case 'password': case 'hidden': case 'textarea': result.push(encodeURIComponent(fieldName) + '=' + encodeURIComponent(field.value)); break; case 'radio': case 'checkbox': if (field.checked) { result.push(encodeURIComponent(fieldName) + '=' + encodeURIComponent(field.value)); } break; case 'select-one': case 'select-multiple': for (var j = 0, jLen = field.options.length; j < jLen; ++j) { if (field.options[j].selected) { result.push(encodeURIComponent(fieldName) + '=' + encodeURIComponent(field.options[j].value || field.options[j].text)); } } // end for break; case 'file': case 'submit': break; // Whether to process? default: break; } // end switch } // end for return result.join('&'); } var form = document.getElementById('target'); console.log(serializeForm(form)); </script>Copy the code

Use native javascript to bind the click event to the li node in the list below, creating an Object when clicked, compatible with IE and standard browsers

<ul id="nav">
    <li><a href="http://11111">111</a></li>
    <li><a href="http://2222">222</a></li>
    <li><a href="http://333">333</a></li>
    <li><a href="http://444">444</a></li>
</ul>

Object:
{
    "index": 1,
    "name": "111",
    "link": "http://1111"
}
Copy the code

script:

var EventUtil = { getEvent: function (event) { return event || window.event; }, getTarget: function (event) { return event.target || event.srcElement; }, // Return the listener successfully registered, IE needs to use the return value to remove listener on: function (elem, type, handler) { if (elem.addEventListener) { elem.addEventListener(type, handler, false); return handler; } else if (elem.attachEvent) { function wrapper(event) { return handler.call(elem, event); }; elem.attachEvent('on' + type, wrapper); return wrapper; } }, off: function (elem, type, handler) { if (elem.removeEventListener) { elem.removeEventListener(type, handler, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, handler); } }, preventDefault: function (event) { if (event.preventDefault) { event.preventDefault(); } else if ('returnValue' in event) { event.returnValue = false; } }, stopPropagation: function (event) { if (event.stopPropagation) { event.stopPropagation(); } else if ('cancelBubble' in event) { event.cancelBubble = true; }}}; var DOMUtil = { text: function (elem) { if ('textContent' in elem) { return elem.textContent; } else if ('innerText' in elem) { return elem.innerText; } }, prop: function (elem, propName) { return elem.getAttribute(propName); }}; var nav = document.getElementById('nav'); EventUtil.on(nav, 'click', function (event) { var event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); var children = this.children; var i, len; var anchor; var obj = {}; for (i = 0, len = children.length; i < len; ++i) { if (children[i] === target) { obj.index = i + 1; anchor = target.getElementsByTagName('a')[0]; obj.name = DOMUtil.text(anchor); obj.link = DOMUtil.prop(anchor, 'href'); } } alert('index: ' + obj.index + ' name: ' + obj.name + ' link: ' + obj.link); });Copy the code

Var a = [‘1’, ‘2’, ‘3’… ; The length of a is 100 and the content is a string filled with random integers. Construct the array A first, and then design an algorithm to deduplicate its contents

Function normalize(arr) {if (arr && array.isarray (arr)) {var I, len, map = {}; for (i = arr.length; i >= 0; --i) { if (arr[i] in map) { arr.splice(i, 1); } else { map[arr[i]] = true; } } } return arr; } /** * fill the array with strings corresponding to 100 random integers. **/ function fillArray(arr, start, end) { start = start == undefined ? 1 : start; end = end == undefined ? 100 : end; if (end <= start) { end = start + 100; } var width = end - start; var i; for (i = 100; i >= 1; --i) { arr.push('' + (Math.floor(Math.random() * width) + start)); } return arr; } var input = []; fillArray(input, 1, 100); input.sort(function (a, b) { return a - b; }); console.log(input); normalize(input); console.log(input);Copy the code