Nezha’s life creed: If you like what you learn, there will be strong motivation to support it.

Take your front end hold to death, every day to learn cool cool, wechat search [programmer Doraemon] pay attention to this different programmer, if you learn things in love will have A strong power support.

Thank you for every programmer who loves the front end, no matter how strange the front end skills are, welcome to pay attention to add me to the group

preface

I hope I can get help for you through this article. (Thanks for one button three times)

1.css3What are the new features

Rounded border-radius, box-shadow, Text-shadow for text, Linear gradient, Transform, Pseudo-element :: Selection, media query, multi-column layout, image border-image.

  1. p:first-of-type, select the first one that belongs to its parent element<p>Each of the elements<p>The element
  2. p:last-of-type, select the last one belonging to its parent element<p>Each of the elements<p>The element
  3. p:only-of-type, select the unique that belongs to its parent element<p>Each of the elements<p>The element
  4. p:only-child, selects each of the unique child elements that belong to its parent element<p>The element
  5. p:nth-child(2), selects each of the second child elements belonging to its parent element<p>The element
  6. :enabled:disabledControls the disabled state of form controls
  7. :checked, a single or check box is selected

2.first-childwithfirst-of-typeIs the difference between the

  1. first-childIt matches the first child of the parent element, structurally speaking
  2. first-of-typeMatches the first element of the type, and the type is the element matched before the colon. (As long as it is the first element of the type, it is not limited to the first child element)
<div>
 <p></p>
 <span></span>
</div>
Copy the code
  • p:first-childMatch to thepElement, becausepThe element isdivThe first child of
  • span:first-childCan’t matchspanElement, becausespanisdivThe second child of
  • p:first-of-typeMatch to thepElement, becausepisdivAll forpThe first child element of
  • span:first-of-typeMatch to thespanElement, becausespanisdivAll is notspanThe first child element of.

3. Solutiontransform:translateProperties flicker

-webkit-backface-visibility: hidden; // Hide the back of the converted element -webkit-transform-style: preserve-3d; Webkit-transform: translated3d(0,0,0); // Enable gpu hardware acceleration mode to render animation using GPU instead of CPUCopy the code

4. How to use it@keyframesmakedivThe element moves 200 pixels

div { widht:100px; height:100px; background: red; animation: move 3s; } @keyframes move{ from{ margin-left: 0px; } to{ margin-left: 100px; }}Copy the code

5. How to implement text wrapping

Use the word-wrap attribute: normal wraps only on permitted hyphenates; Break -word breaks lines inside long words or URLS.

6. Go beyond text ellipsis

When using text-overflow:ellopsis: text overflow, in order not to display ellipsis flags… , clip the overflow part directly.

7.css3How does an animation stay the same at the end of an action

Animation-fill-mode is used, and the value is none, indicating that the default behavior is not changed. The value is forward. After the animation is finished, the last property value is kept. Backwards, applies start property values within the time range specified by animation-delay before animation is displayed; Both, forward and backward fill modes can be applied.

Css3 animation advantages: the performance will be slightly better, the browser will do some optimization of CSS3 animation, the code is relatively simple; Css3 animation shortcomings: animation control is not flexible, compatibility is not good, part of the animation function can not be realized.

8. AdivElement per second50pxThe velocity shifts to the left100px

$('div'),animate({'left': 100}, 2000);
Copy the code
div {
 transition: all 2s linear;
}
div.style.left = {div.offsetLeft+100)+'px';
Copy the code

9. Tell me aboutbox-sizingattribute

The box-sizing attribute controls the parsing mode of the element box model. The default is Content-Box

Content-box allows the element to maintain the W3C standard box model. The width/height of the element is determined by the border+padding+content width/height. Setting the width/height attribute specifies the width/height of the content portion.

Border-box allows elements to maintain the traditional IE box model. Setting the width/height attribute specifies the width/height of the border+padding+content. Under the standard browser, according to the W3C standard parsing box model, once the border or inner margin of the element is modified, it will affect the box size of the element, it has to recalculate the box size of the element, thus affecting the layout of the entire page.

Content-box model:

Width of layout:

width=width + padding-left + paddiing-right + border-left + border-right
Copy the code

Height of layout:

Height = height + padding-top + padding-bottom + border-top + border-bottom
Copy the code

Padding-box model:

Width of layout:

Width = widht (including padding-left + padding-right) + border-top + border-bottomCopy the code

Height of layout:

Height = Height (including padding-top + padding-bottom) + border-top + border-bottomCopy the code

Border-box box model:

Width of layout:

Width = widht (including padding-left + padding-right + border-left + border-right)Copy the code

Height of layout:

Height = height(including padding-top + padding-bottom + border-top + border-bottom)Copy the code

10. How to separate text into 4 columns with 30 pixels between the two columns

div {
 -moz-column-count: 3;
 -webkit-column-count: 3;
 column-count: 3;
 -moz-column-gap: 40px;
 -webkit-column-gap: 40px;
 column-gap: 40px;
 width: 600px;
}
Copy the code

11.background-clipandbackground-orginThe difference between

  • background-clipSpecifies the background, background color, and background image area to draw.

It has three properties:

Border-box: the background is drawn from the border. Padding-box: the background is drawn inside the border. Content-box: the background is drawn from the contentCopy the code
  • background-originSpecifies the location area of the background image

It has three properties: border-box, padding-box, and Content-box (it can only do styling on the background)

12.css3In thetransitionThe property value and meaning are

The transition property is a shorthand property:

  1. transition-propertyWhich attribute needs to be transitioned
  2. transition-durationHow many seconds will it take to complete the transition effect/ms
  3. transition-timing-functionThe velocity effect of the motion curve, e.glinear,ease-in,ease,ease-out,ease-in-out,cube-bezier
  4. transition-delaySpecify a delay time before the transition begins

13. How is visibility defined when an element is not facing the screen

backface-visibility: visible | hidden
Copy the code

14. Howcss3The reflection

-webkit-box-reflect Sets direction and distance. The direction can be below,above,left, or right.

.demo { 
 height: 100px;
 widht: 100px;
 background: url(logo.png);
 -webkit-box-reflect: below 10px;
}
Copy the code

15.css3Achieve a linear gradient of background color

div{
 background: -webkit-linear-gradient(left,red,green 50%, blue)
}
Copy the code

16. Mask the box

.demo {
 height: 100px;
 width: 100px;
 -webkit-mask-image: url(shadow.png);
 -webkit-mask-position: 50% 50%;
 -webkit-mask-repeat: no-repeat;
}
Copy the code

17.animationWhat are the property values

Animation-name is the animation name; Animation-duration is the duration of an animation; Animation-play-state is the playback state (running means play, paused means pause), which can be used to control animation pause. Animation-delay is the animation delay time. Animation-timing-function is the animation motion form, and animation-rotund-count is the number of repetitions. Animation-direction resets before playback.

18.remWhat is the principle of

In responsive layout, by adjusting the font size of the HTML, all elements on the page that use REM units are adjusted accordingly.

19. How do I set this parametercss3Text shadow

H1 {text-shadow: horizontal shadow, vertical shadow, blur distance, shadow color}Copy the code

20. How do I move an element 50 pixels from the left and 100 pixels from the top

div{
 transform: translate(50px,100px);
 -ms-transform: translate(50px,100px);
 -webkit-transform: translate(50px,100px);
 -o-transform: translate(50px,100px);
 -moz-transform: translate(50px,100px);
}
Copy the code

21. How to rotate an element30 °

div{
 transform:rotate(30deg);
 -ms-transform: rotate(30deg); //ie9
 -webkit-transform: rotate(30deg); //safari,chrome
 -o-transform: rotate(30deg); // opera
 -moz-transform: rotate(30deg); // firebox
}
Copy the code

22. The use ofcss3Make a fade in and out animation

@-webkit-keyframes daIn{ from { opacity: 0; } to { opacity: 1; } } @-webkit-keyframes daOut { from{ opacity: 1; } to{ opacity: 0; } } div { -webkit-animation-name: daIn; // animation name -webkit-animation-duration: 3s; // Animation duration -webkit-animation-iteration-count: 1; -webkit-animation-delay: 0s; // Delay time}Copy the code

23. In useBootstrapUse maps at the same timeapiMay causeBootstrapConflict with the map, the map can not be displayed, how to solve

Is mainly in the use of Bootstrap variant zui. CSS when, first of all, open a browser developer tools, see the console without error, if not, check the network resources, and confirm the pictures related to map resources with and without load, if loaded, will call the map code separate from the project, and see if I can, according to the normal If so, in the project, use dichotomy to remove half and half of the referenced JavaScript and CSS code to see if it affects the map API, lock the problem in the UI. CSS, and then check some CSS under the map div in Elements.

24.jqueryIn thedeferredThe function of the

  1. Realize chain operation
  2. Specifies multiple callback functions for the same operation
  3. Specify a callback function for multiple operations
  4. Provides a callback function interface for common operations

25. What isdeferredobject

When you’re developing a website, you’ll encounter some time-consuming javascript operations, such as asynchronous operations such as Ajax reading server data, and synchronous operations such as traversing a large array, that don’t yield immediate results.

You can specify callback functions for them, specifying that they should be called once the run is finished. However, jquery is very weak when it comes to callback functions. To change this, jquery developed deferred objects.

26.jqueryandjquery uiThe difference between

Jquery is a javascript library that provides functions such as selectors, attribute modification, and event binding. Jquery UI is an extension of jquery and a plugin for jquery. Jquery UI provides some common interface elements, such as dialog box, drag behavior, resize behavior, etc.

27. How to use nativeJavaScriptimplementationjquerythereadymethods

$(document).ready() is executed after the DOM is drawn, not after the page is loaded.

Var DOMReady = (function() {var fnList = []; Var ready = false; var fnEvent = null; Function handler(e) {if(ready){return; If (e.type===' onReadyStatechange '&& document.readyState! == 'complete') { return; Var I = 0;} // Run the fnList to prevent more event callbacks from being registered. i<fnList.length; I ++){fnList[I].call(document,e)}; // Remove all callback functions fnList = null; fnEvent = e; } / / register event / / ability to check the if (document. AddEventListener) {document. AddEventListener (' DOMContentLoaded ', handler, false) document.addEventListener('readystatechange',handler,false) window.addEventListener('load',handler,false); }else if(document.attachEvent){ document.attachEvent('onreadystatechange', handler); window.attachEvent('onload', Return function(fn) {if(ready) {fn.call(document,fnEvent)}else {fnList.push(fn)}} Onload = function(){console.log('load')} DOMReady(function(){ console.log('ready') })Copy the code

28.jqueryIn theattrandpropThe difference between

For fixed attributes of HTML elements, use the prop method. When dealing with custom DOM attributes of HTML elements, use the attR method.

29.$.map()and$.each()The difference between

The $.map() method iterates through arrays and objects and returns a new array; The $.map() method is used to map each item of an array or object into a new array.

$.each() is used to iterate over the jquery object and returns the original array, not a new array.

30. jqueryIn how will onejqueryObject converted todomobject

The jquery object is a data object, and you can use the [index] method to get the corresponding DOM object

var $v = $('#v'); // jquery object console.log($v[0]); / / the dom objectCopy the code

Use get(index) :

var $v = $("#v"); console.log($v.get(0)); / / the dom objectCopy the code

31.jqueryThere are several ways to listen for events in

Bind (),live(),delegate(),on(); There are four types of release events: unbind(),die(),undelegate(), and off().

32.jqueryIn agetandeqThe difference between

  • get()Get one of the matched elements,numRepresents the number of matched elements,get()Multiple for collection elements, returnsdomAn array of objects
  • eq()For the firstnZero elements, all starting at zero, returns onejqueryObject.

33.jqueryHow do I execute and stop the bubbling event

Events bubble from the inside out. The stopPropagation() method in jquery is used to stop bubbling, compatible with all browsers

34.jqueryIn thehoverandtoggleThe difference between

Hover () and toggle() are both synthetic events in jquery.

  • hover()The cursor hover method is used to simulate a cursor hover event
  • toggle()Method is used for consecutive alternate click events

35. What data formats have you used

HTML format, JSON format, XML format: HTML fragments provide external data and are generally the simplest; If the data needs to be reused, the advantage in terms of performance and file size is JSON; XML provides the most reliable guarantee of data operability when remote applications are unknown.

36. Selectorid.classWhat’s the difference?

  • id, each in the web pageidYou can only have one name,classIt can be reused

37. How do I set the second check box of the radio button group to selected

$('input[name=items]').get(1).checked = true
Copy the code

38.$.getScript()Methods and$.getJson()What’s the difference

  • $.getScript()Methods can be loaded directlyjavascriptFile, and do not need tojavascriptFile processing,javascriptThe file is automatically executed.
  • $.getJson()Is for loadingjsonFile, usage and$.getScript()The same.

39.jqueryorzeptoWhere does the source code feel good

Jquery’s source code is wrapped in a self-executing environment of anonymous functions to help prevent global contamination of variables.

The Window object can be used as a local variable by passing in the window object argument.

The advantage is that when jquery accesses the Window object, it doesn’t have to push the scope chain back to the top level of the scope, which makes it easier to access the window object. Similarly, passing undefined reduces the risk of undefined being redefined.

(function (window, undefined) {
 window.jQuery = window.$ = jQuery
})(window);
Copy the code

Jquery encapsulates some prototype attributes and methods in jquery. prototype. In order to facilitate access to jquery. prototype, jquery. prototype is assigned to jquery. fn. Some array or object methods are often used, and jQuery saves them as local variables to speed up access. The chained calls implemented by jQuery save code and return the same object, improving development efficiency.

40.jQueryDollar sign in

$(document).ready(function(){
 //...
});
jQuery(document).ready(function(){
 //...
});
Copy the code

41.onload()Functions andready()Difference between functions

  • You can use more than one in a pageready(), but only onceonload()
  • ready()Function on pagedomWhen the element is loaded, andonload()The function is called after all associated resources have been loaded, later than thatready()Function.

42.jQueryWhat are some common selectors in the

Basic selector; Hierarchy selector; Filter selector; Attribute selector; Child element selector; Form selector; Content selector; Visible selector

43. The use ofjQuerySets all element borders on the page to2pxThe width of a dotted line

<script language="javascript" type="text/javascript">
 $("*").css("border", "2px dotted red");
</script>
Copy the code

44. The use ofjQueryImplement a pop-up dialog box when a button is clicked

<button class=" BTN "> jQuery: <script type="text/javascript"> $(function(){ $('.btn').click(function(){ alert('success') }) }) </script>Copy the code

45. How to use itjqueryEncoding and decodingurl

EncodeURIComponent (URL) for encoding, decodeURIComponent(URL) for decoding

46.jqueryIn thedelegate()What does the function do

Delegate () is the semantic method of event delegate in jquery and is used in two situations.

If you have a parent element and need to add events to its children, you can use delegate().

$("ul").delegate("li", "click", function(){
 $(this).hide();
});
Copy the code

When an element is not available on the current page, use delegate()

47. How do I disable the browser forward and back buttons

<script type="text/javascript" language="javascript"> $(document).ready(function() {// forward window.history. / / the back window. The history. The back (); }); </script>Copy the code

48. There are five on the website<div>Element, how to use itjqueryTo choose them

You can use the tag selector to select all div elements. $(“div”) returns a jQuery object with five div tags.

49. How to use it when clicking a buttonjQueryHide a picture

$('.demo-img').click(function() {
 $('.img').hide();
});
Copy the code

50. $(document).ready()What is the function

The ready() function is used to execute code when the document enters the ready state. Jquery allows you to execute code when the DOM is fully loaded. The best thing about using $(document).ready() is that it works in all browsers and jquery helps with cross-browser compatibility issues.

51. How do I find all the selected items in the multi-select drop-down boxes

You can use the jquery selector to get all the selected items that satisfy the multiple=true

$('[multiple] :selected')
Copy the code

52. How do I get the content of all the selected items in the multiple (multiple) checkboxes on the page

$('[multiple] :selected').each(function(index, dom){alert($(dom).text()) // text())})Copy the code

53.$(this)andthisThe key word injqueryThe different

$(this) returns a jQuery object on which you can call multiple jQuery methods, such as text() to get text, on() to bind events, and so on. And this represents the current element, the current DOM element in the context.

54. Extract linkshref

$('a').each(function(){
 alert($(this).attr('href'));
});
Copy the code

Can 55.jqueryDoes the code select all hyperlinks within paragraphs

To select all the hyperlinks a nested inside the paragraph P tag:

$('p a')
Copy the code

56.jqueryIn thedetach()andremove()Differences in methods

The detach() and remove() methods can both remove a DOM element:

  • remove()When you remove the element itself, you also remove everything inside the element, including bound events and those associated with the elementjquerydata
  • detach()While the element itself can be removed, it does not delete data or bind events

57. How to use itjqueryTo add or remove an elementcssclass

Dynamically change the class of an element with the addClass() and removeClass() methods

Use 58.cdnloadingjqueryWhat are the main advantages of libraries

  • Saves server bandwidth
  • Faster downloadsjqueryfile
  • If the browser already from the samecdnDownload thejqueryThe file will not be downloaded again when the page is opened again

59.jQuery.ajax()andjQuery.get()Differences between methods

  • ajax()Methods are more powerful, more configurable, can you specify how long to wait, and how to handle errors
  • get()Method justajax()In the methodgetSimplified approach to requests

60. If you were in ajQueryThe event handler returns itfalseWhat will happen

This will prevent events from bubbling up and default behavior.

61.document.getElementbyId("myId")and$("#myId")Which is more efficient

First, because it uses native methods; The other is the method encapsulated by jQuery, which has to deal with its external judgment logic

62.jQueryThe method chain in is the benefit of using

A method chain is a method that returns an instantiation of the current jQuery object and can continue to call another method.

63. How to usejqueryWill ahtmlElement added todomIn the tree

The appendTo() method adds an HTML element to the DOM tree, using which you can add either an existing element or a new HTML element to the end of the specified DOM element.

append,appendTo,prepend,prependTo,after,insertAfter,before,insertBefore

64. How do you use itjqueryIn theajaxthe

Use load(),$.get(),$.post(), and $.ajax() if you need to set up beforeSend callback, error callback, success callback, complete callback, etc.

65. When importing a page style, uselinkand@importWhat’s the difference?

The difference between:

  1. linkisHTMLThe label,@importiscssProvide.
  2. linkThe imported style page loads at the same time,@importThe introduced styles need to be loaded after the page has finished loading.
  3. linkThere are no compatibility issues,@importIncompatible with IE5 below.
  4. linkCan be achieved byjsoperationDOMDynamically introducing stylesheets to change styles while@importCan’t.

66.HTMLGlobal properties(global attribute)Which (containsH5)?

Global attributes: Attributes used for any HTML5 element

Accesskey: sets a shortcut key class: sets a class identity for an element; Contenteditable: specifies whether the content of an element is editable or not; contextMenu: displays a contextmenu (only supported by Firefox); Data -*: adds custom attributes to an element Dir: Sets element text orientation (default LTR; RTL) draggable: set elements can drag dropzone: drag and drop type set elements (copy | move | link, H5 new attributes, mainstream does not support) hidden: regulation elements have not or not relevant id: element id, Spellcheck: Whether spellcheck is enabled Style: inline CSS style tabIndex: Set elements to get focus, Translate: Does the element and descendant node content need to be localized?Copy the code

Write a method to remove whitespace from a string

var str = '  abc d e f  g ';
function trim(str) {
    var reg = /\s+/g;
    if (typeof str === 'string') {
        var trimStr = str.replace(reg,'');
    }
    console.log(trimStr)
}
trim(str)
Copy the code

68.CSS3What are the new features?

Border: border-radius rounded corner box-shadow border-image Image background: Background_origin Location area of the background image Background-clip Gradient of the drawing area of the background image: Linear-gradient Radial gradient text effect; Word-break word-wrap text-overflow text-shadow text-wrap text-outline text-justify TranslateX (n) translateY(n) Rotate (Angle) scale(n) scaleX(n) translateX(n) translateY(n) Rotate (Angle) scale(n) scaleX(n) Rotate (n) rotate(Angle) matrix(n,n,n,n,n,n) rotate(Angle) matrix(n,n,n,n) 3D transform: Translate3d (x,y,z) translateX(x) translateY(y) translateZ(z) translate3D (x,y,z) translateX(x) translateY(y) translateZ(z) Scale3d (x,y,z) scaleX(x) scaleY(y) scaleZ(z) RotATE3D (x,y,z, Angle) rotateX(x) rotateY(y) rotateZ(z) Perspective (n) Transitions Transition Animation @KeyFrames Animation Flexbox Multimedia query @mediaCopy the code

69. Using recursive algorithm, the array length is 5 and the random number of elements is in2-32Values that are not duplicated between

var arr = new Array(5);
var num = randomNumber();
var i = 0;
randomArr(arr,num);
function randomArr(arr,num) {
    if (arr.indexOf(num)< 0){
        arr[i] = num;
        i++;
    } else {
        num = randomNumber();
    }
    if (i>=arr.length){
        console.log(arr);
        return;
    }else{
        randomArr(arr,num)
    }
}
function randomNumber() {
    return Math.floor(Math.random()*31 + 2)
}
Copy the code

70. Write an encrypted string method

Encode (STR) {return btoa(encodeURIComponent); } function decode (str) { return decodeURIComponent(atob(str)); }Copy the code

71. What are the communication methods between multiple tabs in the browser?

WebSocket (cross-domain) 2. PostMessage (cross-domain) 3.SharedWorker 4. Server-sent Events 5 7.CookiesCopy the code

72. Briefly describe your understanding of elegant degradation and progressive enhancement

Elegant downgrade, first do a complete version with a complete experience, and then do compatibility down.

Incremental enhancement, where you build a version that works, and then slowly enrich the experience and content.

73.viewportWhat are the common Settings?

Width Sets the layout viewport width as a positive integer, or the string "width-device" initial-scale sets the page's initial scale as a number, including minimum-scale, the minimum size allowed by the user. For a number, maximum-scale is the maximum value that the user is allowed to scale. For a number, height is the height of the layout viewPort. This property is not important to us. User-scalable Is rarely used to allow users to scale, with a value of "no" or "yes", where no stands for not allowed and yes stands for allowedCopy the code

Viewport is controlled within the meta tag.

<meta name="viewport" content="width=device-width ", Initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = 0 "/ >Copy the code

74. By comparisonPx, EM, REMWhat’s the difference?

Default: 1em = 10px; 1rem = 16px

Px is the logical pixel in CSS and there is a ratio between the physical pixel on the mobile and DPR EM is the size relative to the parent element and R in REM is root, the size relative to the root element (HTML tag)

75. Briefly describe what a callback is and write an example

dom.addEventerlisten('click',function(){
  // do something
})
Copy the code

76. What is your understanding of semantic labeling?

See the name know meaning, convenient for many people to know, and named unified, concise, easy to reconstruct the code

77. What are some ways to hide elements on a page?

display: none
opacity: 0
visibility: hidden
z-index: -9999999999999
transform: scale(0)
margin-left: -100%
position: relative; left: -100%
width: 0; height: 0;
Copy the code

78. Removes the last specified character in a string

function trim(str) { if(typeof str === 'string'){ var trimStr = str.substring(0,str.length-1) } return trimStr; }
Copy the code

79.HTML5How to use offline storage of files and how does it work?

Localstorge uses the browser’s local storage to cache information and import the created data when it is created

// add localstorage.setitem ('myCat', 'Tom'); // get let cat = localstorage.getitem ('myCat'); // Delete all localstorage.clear ();Copy the code

80.CSSWhat are the selectors? Which attributes can be inherited?

Selectors wildcard ID class tag descendant selectors child selectors sibling selectors property selectors pseudo-class selectors pseudo-element selectors can inherit properties font size font weight font style font family colorCopy the code

81. Explain hyperlinkstargetThe value and effect of the attribute

The target attribute of the tag specifies where to open the linked document.

Attribute values:

_blank opens the linked document in a new window. Love the default. Open the linked document in the same framework. _parent opens linked documents in the parent framesite. _top opens linked documents throughout the window. Framename opens the linked document in the specified frame.Copy the code

82.CSS3What are the new pseudo classes and briefly describe them

83.labelWhat are the functions

<label for="hobby"> hobby </label> <input ID ="hobby" type="checkbox" value="0">Copy the code

The role of the < label >

Represents a description of an element in the user interface

Added hit area where screen reader can read labels. Users of assistive technologies have an easier time understanding which data to input

Use label to “emulate” a button to solve the problem of different browser native button styles

There are too many examples of pure CSS state switches combined with checkbox and Radio form elements. For example, control CSS animation playback and stop

The input focus event triggers anchor location, and we can use label as a trigger for TAB switching

84. WithcssCreate a triangle and describe how it works

 width: 0;
height: 0;
margin: 100px auto;
border-top: 50px solid transparent;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid red;
Copy the code

The principle is that the width and height are fixed on both sides, and the border is different with color and can be modified with top, right, bottom and left options. The width and height should be zero when in use. Triangles need mathematical knowledge (Pythagorean theorem) to be considered equilateral and congruent.

<div class='rect'></div>
<style>
  .rect {
    width: 0;
    height: 0;
    background-color: #fff;
    border-right: 100px solid rgb(34, 230, 220);
    border-left: 100px solid rgb(202, 146, 25);
    border-top: 100px solid rgb(29, 156, 194);
    border-bottom: 100px solid rgb(16, 204, 101);
  }
</style>
Copy the code

Create a div with width and height 0. Create a div with width and height 0. Create a div with width and height 0

<style>
  .rect {
    width: 0;
    height: 0;
    background-color: #fff;
    border-right: 100px solid transparent;
    border-left: 100px solid transparent;
    border-top: 100px solid rgb(29, 156, 194);
    border-bottom: 100px solid transparent;
  }
</style>
Copy the code

85.IframeWhat’s the upside? What’s the downside? What well-known websites are still used in ChinaIframeWhy? What used to be discarded now? And why?

The original use of iframe is now anachronistic and problematic, but its other features are good black magic.

  • Used to implement long connections
  • Cross-domain communication
  • Historical record management, resolvedajaxMake web sites responsive to browser forward and back buttons in the solutionhtml5thehistory apiWhen not available as an alternative.
  • The front of a pureutf8andgbkEncoding transfers

Now, examples of iframe that should be used are:

  1. Sandbox isolation.
  2. References to third party content.
  3. Standalone interactive content, such as slides.
  4. Need to maintain independent focus and history management of sub-windows, such as complexWebApplications.

Note: Iframe may not be appropriate for login pop-ups. The HTML standard has added a dialog element, which may be more appropriate.

86. Briefly describe your views onBFCSpecification understanding

BFC stands for Block Formatting Context, as well as IFC. A BFC is like a “bound.” If a DOM element has a BFC, its inner children do not affect the outer elements. The elements outside do not affect the elements inside.

The most common example is to clear float overflow: hidden; Properties. overflow: hidden; The ELEMENT’s BFC is triggered so that float elements inside it do not affect the layout of external elements.

Conditions for triggering the BFC:

< HTML > Root element float is not none overflow is auto,scroll,hidden display is table-cell, Table -caption,inline-block position of any value is not static and relative BFC can achieve more robust adaptive layout.Copy the code

Reference article: CSS World

87. Count the number of occurrences of one character or string in another string

var childInNums = parent.split(child).length - 1
Copy the code
function strCount(str, target) { let count = 0 if (! target) return count while(str.match(target)) { str = str.replace(target, '') count++ } return count } console.log(strCount('abcdef abcdef a', 'abc'))Copy the code

88. What are the advantages and disadvantages of clearing float?

  1. By setting the parent labeloverflow: auto
  2. throughafterPseudo classes:{display: block; content: ''; clear: both; }

Trigger BFC or Clear: both

CSS box collapse Solution Solution

89. Give me a brief descriptionJSWhat are the built-in objects

Time Object Date String Object String Mathematical Object Math numerical Object Number Array Object Array Function Object Function parameter collection Boolean Object Error Basic Object ObjectCopy the code

90. What are common browser kernels?

The kernel can be divided into rendering engine and JS engine by function.

The browser kernel is often referred to as the browser’s rendering engine.

Internet Explorer: Trident Safari (apple's own browser) : WebKit FireFox: Gecko Chrome: Blink, with a V8 ENGINE Opera: BlinkCopy the code

91. Understanding of box models

The box model mainly consists of the following parts:

Padding (content) border (margin)Copy the code

There are two types of box models:

Standard box model (W3C box model) Standard box model width = content

IE box Model Width = padding + border + Content of the IE box model

By default, boxes are boxes based on the standard box model.

In CSS3 there is the box-sizing property, which changes the box model of the default box. The two values of this attribute are content-box (standard box model) and border-box (IE box model).

Understanding the box model

92.html5In theformHow do I turn off autocomplete?

Set the Form’s AutoComplete property to off

93.::beforeand:afterWhat’s the difference between a single colon and a double colon

Difference: Pseudo-elements already existed in CSS1 with single colons, but were revised in CSS3 with double colons ::before ::after to indicate pseudo-elements and to distinguish pseudo-classes. Function: Appends content to elements before (::before) and after (::after)Copy the code

What does the [CSS] property content do? What scenarios are available?

94. Tell me your understanding of javascript’s scope

1: global scope 2: local scope

Prior to ES5, javascript was functional scoped, not block-scoped. Variables in if or for braces are actually accessible in the outer layer.

for(var i = 0; i < 10; i++){var j=123}
console.log(j) // 123;
Copy the code

However, with ES6’s let and const, you can implement block-level scoping.

var a = 1; function b(){ var b = 2; console.log(a); Function c(){var a = 4; var c = 3; console.log(a); // 4 does not pollute console.log(b); // 2 } c(); } console.log(b()); console.log(a);Copy the code

95.httpWhat are the status codes?

200 Success 301 Redirect 304 (unmodified) The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned. 400 (Error request) Server does not understand the syntax of the request. 403 (Forbidden) The server rejects the request. 404 (Not found) The server could not find the requested page. 500 (Server internal error) The server encountered an error and could not complete the request. The 501 (not yet implemented) server does not have the capability to complete requests. For example, the server may return this code if it does not recognize the request method. 502 (Error Gateway) server, acting as gateway or proxy, received invalid response from upstream server. 503 (Service unavailable) The server is currently unavailable (due to overloading or downtime for maintenance). Usually, this is a temporary state. 504 (Gateway Timeout) The server acted as a gateway or proxy, but did not receive the request from the upstream server in time. 505 (HTTP version not supported) The server does not support the HTTP protocol version used in the request.Copy the code

96. WhyHTML5You just need to write<! DOCTYPE HTML>You can

Because HTML5 is based on a different benchmark than HTML4.

HTML4 was based on SGML and therefore needed to introduce a DTD in addition to a DOCTYPE to tell the browser what standard to use for rendering. DTDS are also divided into standard schemas and strict schemas. If you don’t write anything and leave the browser to its own devices, it will go into weird mode.

HTML5 is not based on SGML, so don’t follow it with a DTD, but you need a DOCTYPE to regulate the browser’s rendering behavior.

Note: SGML is a collection of common markup languages. There is HTML, XML, so you need a DTD to specify which specification to use.

97. What is a closure? What are the pros and cons?

  • Closures: Local scope references variables of the upper (non-global) scope
  • Advantages: Prevents variable contamination of the scope
  • Disadvantages: Memory leaks if not released

98. Write a method to remove the weight of an array

A one-dimensional

new set(... arr)Copy the code

A two-dimensional

arr.reduce((a,b)=>{ return new set(... a.concat(b)) },[])Copy the code

99. The elementaltandtitleWhat’s the difference?

The title attribute is a tag that adds supplementary information to each element. When the mouse pointer is placed over an element, the main function is to display a tooltip.

Alt is the attribute that specifies alternative text for an image

Alt is the attribute tag specified in that represents the image.

As I wrote it as a substitute text, it is used in situations where text rather than images is required.

  • If a blind person uses the speech reading function, the image will be read aloudaltProperty.
  • The image is displayed when it cannot be displayed due to a broken link.
  • GoogleandYahoo!Wait for the robot to grab the picture.

100.tableWhat are the advantages and disadvantages of?

Table is used to display table data, and it is in line with people’s intuitive cognition.

Before div+ CSS layouts became popular, tables were commonly used for layout.

The nice thing about table layouts is that they are easy to control, especially centered and aligned. The disadvantage is that there are too many DOM nodes, which can lead to slow page loading and not good for SEO. As a result, the table layout soon became a thing of the past as CSS matured.

101. typeof('abc')andtypeof 'abc'Are allstring, thentypeofOperator or function?

If typeof is a function, calling Typeof (Typeof) should return a string ‘function’, but the actual operation returns an error, so Typeof is not a function

Typeof is the operator, explicitly defined in MDN, used to type the return of a trailing expression.

102. Say you are rightSVNandGITUnderstanding and distinction

SVN is centralized, GIT is distributed

103. What isFOUC? How did you avoid itFOUC?

FOUC: Style changes suddenly when loading

Reason: Because when rendering HTML, CSS stylesheets are encountered and the HTML is re-rendered

Instead of putting the stylesheet inside the head, use @import to import the style

Solution: Try to place the stylesheet on top of the body tag

104.cssThe properties of thecontentWhat does it do?

The content attribute is used in conjunction with ::before and ::after pseudo-elements to generate text content

105."attribute"and"property"What’s the difference?

  • propertyisDOMProperty, isJavaScriptIn the object
  • attributeisHTMLA property on a tag whose value can only be a string

Write a way to verify your ID number

Address code 6 bits + year code 4 bits + month code 2 bits + Date code 2 bits + Sequence code 3 bits + parity code 1 bit

107. For HTML form input fields,Disabled = "disabled" and readonly = "readonly"What’s the difference?

Similarities: both text boxes become read-only, not editable

The disabled property grays the input text box as well as making it read-only and uneditable, but readOnly does not.

Input elements with the readonly attribute can still get focus, but input elements with the Disabled attribute cannot

Readonly is valid only for input and TextaREA, while disabled is valid for all form elements.

Readonly: uneditable, copy-able, selectable, can receive focus but cannot be modified, the background receives the passed value

Disabled: Cannot edit, copy, select, receive focus, or receive background values

108. Say you are rightline-heightHow to understand?

The line height is the distance between the baseline of two lines of text.

The red line is the baseline

Baseline refers to the bottom line of a line of characters. Baseline is not the bottom edge of a Chinese character, but the bottom edge of the English letter X.

109. Tell me your understanding of redrawing and rearrangement and how to optimize it.

A DOM tree and a CSSOM tree are generated when a browser loads a web page

Redraw:

Once the box position, size, and other properties, such as color and font size, have been determined, the browser draws the primary colors according to their characteristics and renders the content on the page. Redraw is the behavior of the browser triggered by a change in the appearance of an element. The browser redraws the element based on its new attributes to give it a new appearance.

Conditions that trigger a redraw: changes the appearance attributes of an element. Font-size: 14px; background-color; font-size: 14px;

Rearrangement (reflux) :

Reflow occurs when part (or all) of a rendering tree needs to be rebuilt due to changes in the size, layout, hiding, etc. Each page needs to be refluxed at least once, the first time the page loads.

The relationship between redraw and rearrangement: During backflow, the browser invalidates the affected part of the render tree and reconstructs that part of the render tree. When backflow is complete, the browser redraws the affected part to the screen. This process is called redraw.

So rearrangement must lead to redrawing, but redrawing does not necessarily lead to rearrangement.

Conditions that trigger reordering: Any changes in page layout and geometry will trigger reordering

Such as:

1. Page rendering initialization (unavoidable)

Add or remove visible DOM elements.

3. Changing the position of elements, or using animation;

4. Element size changes — size, margins, borders;

5. Change of browser window size (when resize event occurs);

6. Conditions for rearrangement triggered by the change of filling contents: changing the size and position of elements, such as width, height, pading, margin, position, etc., adding and deleting DOM operations, etc

The cost of redrawing and rearranging: time consuming, resulting in a slow browser.

110.0.1 + 0.2, 0.1 + 0.3 and 0.1 * 0.2What are they equal to? And explain why?

111.newWhat is the understanding of operators? Implement one manuallynewmethods

The new operator creates an instance of a user-defined object type or one of the built-in object types with a constructor

New Object() example:

  • Create a new object
  • Points the new object’s prototype to the constructor’s prototype
  • Point this in the constructor to the new object
  • Return this new object

112.jqueryHow do classes operate in

Append classes with addClass(), remove classes with removeClass(), and toggle().

How do I dynamically add new elements to jQuery and bind events to newly produced elements

JQuery’s HTML () can add new elements to the current element. Binding events directly before an element is generated is definitely not effective because the bound element does not currently exist. So you can use the Live method to dynamically bind events.

113. UsejQueryIn the animation

  • hide()andshow()You can modify multiple style attributes at the same time, such as height, width, and opacity.
  • fadeIn()andfadeOut().fadeTo()You can only change the opacity.
  • slideUp()andslideDown().slideToggle()You can only change the height.
  • animate()A method that belongs to a custom animation and can customize properties.

114. After clicking the hyperlink, it will automatically jump, and after clicking the “Submit” button, the form will be submitted, etc. Sometimes, in order to prevent the default behavior, what should I do

Either use event.preventDefault() or return false in the event handler

115. What method do you use to submit data

The $.post() method is generally used, and $.ajax() is used if you need to set the beforeSend callback before submission, error callback after failure, success callback after complete request, etc.

In 116.ajaxThere are several main ways to obtain data in

Three: HTML concatenated Query data, JSON array object data, and form data serialized by the serialize() method.

117.jqueryWhich methods of inserting nodes have been used in

Internal insert methods: Append (), appendTo(), prepend(), prependTo()

External insert methods: after(), insertAfter(), before(), insertBefore()

In 118.jqueryHow do I get or set a property? How to Delete attributes

Jquery uses the attr() method to get and set element attributes, and removeAttr() method to remove element attributes.

119. How to set and obtainhtmlAnd the value of the text

Use the HTML () method, similar to the innerHTML attribute, to read or set the HTML content of an element.

The HTML () method can be used for XHTML documents, not XML documents.

  1. text()Method can be used to read or set the text content of an element
  2. val()Method can be used to set or get the value of an element

120. Tell me about<script>, <script async>, and <script defer>The difference between

The

<script>

When the Script tag is placed in the head and only the SCR attribute of the script tag is introduced into the external JS file, the HTML file starts rendering until the script tag hits, at which point parsing stops and a request is found to fetch the file and execute. Inherit render HTML tags before execution ends.

<script async>

Async means asynchronously loading a JavaScript file.

Async will download the file during HTML parsing, pause the HTML parsing after downloading, execute the downloaded external JS file, and continue parsing the HTML after execution.

<script defer>

What defer means is that you are executing the loaded JavaScript file after the HTML document has been parsed.

The difference between async and ASYNc is that external JS files are also downloaded during HTML parsing, but the JS script file is not executed immediately after the download, but after the HTML parsing is complete. Execute downloaded external JS files between DOMContentLoaded

121. Say you are rightz-indexThe understanding of the

The Z-index attribute sets a Z-order for locating an element and its descendants or flex items. When elements overlap, the larger z-index element will overwrite the smaller element in the upper layer display.

122. What are the methods for wrapping nodes? What are the benefits of wrapping nodes?

Methods for wrapping nodes: wrapAll(), wrap(), wrapInner(), which can be used when inserting additional structured tags into a document because it does not break the semantics of the original document.

123. How to implement adaptive layout

  • You can use media queries to create responsive pages
  • withBootstrapThe grid system
  • Use elastic box models

124. How to improve user experience on mobile terminal

  • Clear visual vertical line
  • Grouping of information
  • Extreme subtraction
  • Use selection instead of input
  • The way labels and text are arranged
  • The password is confirmed in plain text
  • Use your keyboard wisely

125. How to solve the problem of blinking back when I hold down the page for a long time

element {
 -webkit-touch-callout: none;
}
Copy the code

126. The solutioniPhoneAs well asiPadA problem with the default inner shadow of the input box

element {
 -webkit-appearance: none;
}
Copy the code

127. How to solve the failure of Round corners of Android Phones

Style invalidated elements with background-clip:padding-box

128. How to solve this problemiosSet in theinputButton style overrides the default style

input,
textarea {
 border: 0;
 -webkit-appearance: none;
}
Copy the code

129. How to solve mobile terminalclickEvents have300msLatency issue

The 300ms delay leads to poor user experience. In order to solve this problem, the click event is usually replaced by the event simulated by TouchStart, Touchend, Touchmove, and tap on the mobile end.

130. How to solve mobilehtml5In thedateThe type ofinputTag not supportedplaceholderProblem with attributes

<input placeholder=" placeholder "type="text" onfocus="(this.type='date')" name="date">Copy the code

131. How do I disable copying or selecting text

Element {
 -webkit-user-select: none;
 -moz-user-select: none;
 -khtml-user-select: none;
 user-select: none;
}
Copy the code

132. Solve the lag problem when dragging the scroll bar up and down

body {
 -webkit-overflow-scrolling: touch;
 overflow-scrolling: touch;
}
Copy the code

133. Tell me aboutXHTML

  • All of theXHTMLThe element must be nested within the root element.
  • XHTMLTags must be closed
  • XHTMLAll tags must be lowercase
  • XHTMLTags must be properly nested

134. Why10.toFixed(10)Complains?

The reason is that the JS interpreter pairs. The interpretation of the ambiguous result. It can be understood as either a decimal point or a call to a method. According to the specification, the interpreter judges it to be a decimal point.

135.DOMandBOMWhat’s the difference?

BOM refers to the browser object model

DOM refers to the document Object Model

Note: DOM and BOM are only available when the JS host environment is a browser, not in Node.

The relationship description is as follows:

136. What problems are captcha designed to solve?

  • Prevent machine behavior, make sure it is human operation, such as login, Posting, etc.
  • Secure the server, for example12306Buying tickets, all kinds of shopping.

Type of verification code:

Graphic verification code; Mobile verification code

Write a method to get the maximum and minimum value of an array

Math.max.apply(Array,[25,62,91,78,34,62]) // 27 array.prototype Function () {return math.max. Apply (null, this)} let arr = [1,2,3,4] math.max (... arr) Math.min(... arr)Copy the code

138.cssIs the weight calculation rules

139. Enter the URL to the page display

You can bring up caching, DNS resolution, TCP connections, HTTP requests, rearrangement and redrawing, and many more sub-issues.

140.rgba()andopacity

  • opacityIs a property,rgba()It’s a function. It’s a property value
  • opacityApplies to the element and its content, and the content inherits the element’s transparency, values0-1
  • rgba()Usually used as a background colorbackground-colorOr colorcolorAttribute value, transparency by whichalphaThe value is valid0-1

141. TheargumentsIs it an array?

Arguments is an array-like object that can only be accessed inside non-arrow functions. Arguments can be converted to an Array using array.from (arguments). There are no push and pop methods except for length and index access.

142. Tell me aboutBind, call, applyThe difference between? And implement one by handbindThe method of

Call and apply both solve the problem of changing the direction of this; The function is the same, but the way the parameter is passed is different. Call can accept a list of arguments, apply accepts only an array of arguments

Bind returns a new function, not executed.

Function.prototype.myCall = function (context = window) { context.fn = this; var args = [...arguments].slice(1); var result = context.fn(... args); delete context.fn; return result; } Function.prototype.myApply = function (context = window) { context.fn = this; Var result = context.fn(arguments[1]) {result = context.fn(... arguments[1]) } else { result = context.fn() } delete context.fn return result; } Function.prototype.myBind = function (context) { if (typeof this ! == 'function') { throw new TypeError('Error') } var _this = this var args = [...arguments].slice(1) return function F() { if (this instanceof F) { return new _this(... args, ... arguments) } return _this.apply(context, args.concat(... arguments)) } }Copy the code

143. Say you are rightthisThe understanding of the

Global this is window; The function this is the caller; The constructor’s this is the new object after new, and the first argument to call and Apply Bind’s this

144. How to resolve block attribute tag float after setting levelmarginIn the case ofie6Shown in themarginBigger problem than set.

Add display:inline to float’s label style control to convert it to an inline property.

145. Why image elements on a page have spacing by default.

Because img tags are inline attributes, they are placed on a line as long as they are within the width of the container, but in some browsers there is a gap between the IMG tags.

Solutions when spacing occurs:

  • You can usefloatAttribute toimgLiquid layout
  • Can be achieved byfont-sizeProperty sets the whitespace size to 0
  • Can put the picturedisplayProperty set toblock

146. How to implement the box model

Margin >padding>width(content) box-sizing: border-box; Margin >width(border>padding>content) box-sizing: content-box; }Copy the code

147. How to solve itliGaps occur when floating elements occur within an element

To resolve the problem, set vertical-align to top, middle, or bottom

148. How to make long words and longer wordsurlconversion

Use word-break:break-all breaks a line inside the word.

149. How can I solve this problemdisplay:inine-blockinie6.ie7Under incompatible issues

Set the float:left property

150. How to solve itie6Does not supportposition:fixedProblem with attributes

Ie6 uses position: Absolute and javascript to simulate, or does not use the fixed attribute at all.

151. How do I get custom attribute data

Under IE, custom attribute data can be obtained using the same method as getting regular attributes, or by using getAttribute().

Under Firefox, you can only get custom attribute data using getAttribute().

So use getAttribute() to get custom attribute data.

152. Tell me aboutevent.srcElementcompatibility

Under Ie, the even object has the srcElement property, but not the target property.

In Firefox, the even object has a target attribute, but no srcElement attribute.

By using srcObj = event.srcElement? Event. SrcElement: event. The target is compatible with all browsers this way.

153. Tell me aboutbodyLoading problem

  • Firefox’s body object exists before the body tag is fully read by the font.

  • The Body object of Internet Explorer must exist after the body tag has been fully read by the browser.

154. How to achieve horizontal centering of elements

Block elements:

margin: 0 auto;
Copy the code

Line element: use parent element selector {text-align:center; }

155. How to makepThe element is vertically centered

Use vertical-align:middle to increase the line spacing to the same height as the entire P, then insert the text to center it vertically.

156.marginDouble problem of

P set to float doubles margin under ID. This is a bug in IE6. Solution: add: display:inline to p

.demo {
 float: left;
 margin: 5px;
 display: inline;
}
Copy the code

157. How to solve itie6The following picture has a gap problem

Can change the HTML layout, set the img to display: block, or set the vertical – the align attribute to vertical – align: top/bottom/middle/text – bottom

158. How do I align the text with the text input field

You can add the vertical-algin: middle attribute to the input box.

159. The solutionieUnable to set scroll bar color

Replace body with HTML

160. The solutionformLabel margins are incompatible

ul, form {
 margin: 0;
 padding: 0;
}
Copy the code

161. Characteristics of constructors

The constructor, whose function name is capitalized, is like a template and can be executed using the new keyword to create the instantiated object.

162.javascriptAn implementation method inherited from

Instances of subclasses can share methods of the parent class, and subclasses can override methods extended from the parent class.

163. How do I get throughnewConstruct the object.

Create a new object of type Object and point this variable to it. Points the prototype of the object to the prototype of the constructor; Execute the constructor to add its own property method to the instantiated object via this object; Returns the newly created object referenced by this.

function demo(dada) {
 var obj = {};
 // this = obj;
 obj.__proto__ = dada.prototype;
 Work.call(obj);
 return obj
}
Copy the code

164. Object-oriented features

Abstract; Encapsulation; Inheritance; polymorphism

165. Overview of three characteristics of Object-oriented programming

Encapsulation: Define properties and methods that describe the same object in one object.

Inheritance: Properties and methods in the parent object are used by the quilt object.

Polymorphic, where the same object takes on different shapes in different situations: overloading (the same method name, depending on the parameters passed in, and different operations); Override (when a child inherits a property or method from its parent, it defines a new property or method to override the property or method inherited from the parent)

166.thisCommon direction

At run time, the this keyword points to the object on which the method is being called

167. Implement object inheritance

Object.setprototypeof (Child, parent)Copy the code
Constructor. Prototype = objectCopy the code
var demo = Object.create(obj)
Copy the code

168.JSONPAchieve cross-domain

In HTML, the script tag is dynamically inserted, and a javascript file is introduced through the script tag. After the javascript text is successfully loaded, the function specified in the URL parameter will be executed, and the required JSON data will be passed in as the parameter.

169.ajaxrequest

function ajax(url,fn){
 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if(xhr.readyState === 4){
   if(xhr.status === 200){
    fn && fn(JSON.parse(xhr.responseText));
   }
  }
 }
 xhr.open('GET',url, true);
 xhr.send(null);
}
Copy the code

170. Asynchronous loading

  • Set up thedeferProperty to delay script execution, supported onlyie.
  • Set up theasyncProperty to load scripts asynchronously.
  • createscriptTag and insertDOMAfter the page is rendered, the callback function is executed.

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.dadaqianduan.cn/#/

Star: github.com/webVueBlog/…