The 2022 front end has been cleaned up

foreword

This article is a collection of front-end topics, most of which are from Niuke.com , and the answers are based on my own understanding and summary. If there are any mistakes, please correct me, so as not to mislead more people! ! !

Pending update! ! !


CSS

CSS priority

From high to low are:

!important>行内样式>ID选择器>类选择器>标签选择器>通配符选择器>继承>浏览器默认样式

JavaScript

new Array(10)

When we create an array through a constructor with a single numeric parameter, the length of the array is the parameter passed in, and the elements in it are undefined. So when you use push to insert elements at the end of the array, the length of the array will change from 10 to 11.

let arr = new Array(10);//注意,这里代表数组长度为 10
arr.push(1);
arr.slice(0,5);//slice 方法返回一个新数组,不会改变原数组
console.log(arr.length);//11

Throttling implementation

定义: Throttling means that it only runs once within n seconds. If it is triggered repeatedly within n seconds, it will take effect only once.

功能

  • In order to limit the execution frequency of the function, the response speed caused by the high trigger frequency of the optimized function cannot keep up with the trigger frequency, and the phenomenon of delay, suspended animation or freeze occurs.
  • save resources
// 定时器
function ttrothle(func,delay){
    
    
      let timer=null;
      return function(){
    
    
          if(!timer){
    
    
              timer=setTimeout(()=>{
    
    
                  timer=null;
                  func.apply(this,arguments)
              },delay)
          }
      } 
  }
// 时间差
function ttrothle(func,delay){
    
    
      let prev=0;
      return function(){
    
    
          let now= Date.now();
          if(now-prev>=delay){
    
    
              func.apply(this,arguments);
              prev=now;
          }
      } 
  }

Demonstration example:

<body>
    <div>
        我是节流处理后的:<input type="text">
    </div> 
    <script>
        function ajax(value){
    
    
            console.log('value:'+value+',time:'+Date.now());
        }

        // function ttrothle(func,delay){
    
    
        //     let timer=null;
        //     return function(){
    
    
        //         if(!timer){
    
    
        //             timer=setTimeout(()=>{
    
    
        //                 timer=null;
        //                 func.apply(this,arguments)
        //             },delay)
        //         }
        //     } 
        // }

        function ttrothle(func,delay){
    
    
            let prev=0;
            return function(){
    
    
                let now= Date.now();
                if(now-prev>=delay){
    
    
                    func.apply(this,arguments);
                    prev=now;
                }
            } 
        }

        var input = document.querySelector('input')
        let ttrothleHandle=ttrothle(ajax,3000)
        input.addEventListener('keyup',function(e){
    
    
            ttrothleHandle(e.target.value)
        })

    </script>   
</body>

es6 new data type

BigIntis a built-in object that provides a way to represent 2^53 - 1integers greater than .

A BigInt can be defined by appending n to an integer literal, eg: 10n, or by calling the function BigInt() (but without the new operator) and passing an integer or string value.

//const alsoHuge = BigInt(9007199254740991);
// ↪ 9007199254740991n
var bg = 10n
console.log(typeof bg); //bigint

var s=Symbol('joney')
console.log(typeof s); //symbol

How transition detects the end of animation

transitionendThe event will be fired after the CSS transition ends. When the transition is removed before the transition is completed, for example, the transition-property property of CSS is removed, the event will not be fired. If the display is set to "none" before the transition is completed, the event will also not be fired. will be triggered.

function showMessage() {
    
    
    console.log('Transition 已完成');
}

var element = document.getElementById("slidingMenu");
element.addEventListener("transitionend", showMessage, false);

Talk about the value of box-sizing and the corresponding role

  • content-boxis the default value. If you set an element's width to 100px, then the element's content area will be 100px wide, and any border and padding widths will be added to the width of the last drawn element.
  • border-boxTell the browser that the border and padding values ​​you want to set are contained within width. That is, if you set the width of an element to 100px, then the 100px will include its border and padding, and the actual width of the content area is the value of width minus (border + padding). In most cases, this makes it easier to set the width and height of an element.

Centered horizontally and vertically

(1) Horizontal centering: text-align:center;. Center vertically: line-height:XXpx;line-height is set to the height of the parent box.

(2) Implemented using flex

  • display: flex;Set the display property to flex to define it as a flex container
  • align-items: center;Defines how items are aligned on the cross axis (vertical axis), centered vertically
  • justify-content: center;Defines the alignment of the item on the main axis, centered horizontally

Image lazy loading

Improve page loading and rendering speed, thereby improving user experience and reducing server pressure.

<script>
    var num = document.getElementsByTagName('img').length;
    var img = document.getElementsByTagName("img");
    var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历

    lazyload(); //页面载入完毕加载可是区域内的图片
    window.onscroll = lazyload;
    function lazyload() {
    
     //监听页面滚动事件
        var seeHeight = document.documentElement.clientHeight; //可见区域高度
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
        for (var i = n; i < num; i++) {
    
    
            if (img[i].offsetTop < seeHeight + scrollTop) {
    
    
                if (img[i].getAttribute("src") == "default.jpg") {
    
    
                    img[i].src = img[i].getAttribute("data-src");
                }
                n = i + 1;
            }
        }
    }
</script>

Image loading jittery

When the padding of block-level elements (such as div, p) is set to a percentage, it is determined according to the width of the container

.wrapper{
    
    
   width:100%;
   height:0;
   padding-top:24.25%; <--!在这里我们也可以使用padding-bottom属性进行设置--> 
}

promise.then() chaining

The then method returns a new Promise instance (not the original Promise instance!! It's a new one). You can use return to pass parameters, the default is undefined.

new Promise((resolve, reject) => {
    
    
     resolve(123);
 }).then(data => {
    
    
     console.log(data); // 123
 }).then(data => {
    
       
     console.log(data);  // undefined
 })

scope

  let a=10;
   var b=20;
   function fn(){
    
    
       console.log('a ',a);  // 10
       console.log('this.a ',this.a); // undefined
       console.log('this.b ',this.b);  // 20
       console.log('b ',b);  // 20
   }
   fn();
  • let m = 10;time output NaN NaN 6.
  • var m = 10;output11 11 6
 let m = 10;
 function fn() {
    
    
     return this.m + 1;
 }
 var obj = {
    
    
     m: 5,
     test1: function() {
    
    
         return fn();
     }
 };
 obj.test2 = fn;
 console.log(obj.test1(), fn(), obj.test2())
var obj = {
    
    
     m: 5,
     test1: function() {
    
    
         console.log(this.m); // 5
         return function (){
    
    
             console.log(this.m); //undefined
         }
     }
 };
 obj.test1()();

url parameter extraction

decodeURIComponent()Methods are used to encodeURIComponentdecode parts of Uniform Resource Identifiers (URIs) encoded by methods or other similar methods.

decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_шеллы"

decodeURI()Functions can decode encodeURIUniform Resource Identifiers (URIs) obtained by creation or other processes.

const uri = 'https://mozilla.org/?x=шеллы';
const encoded = encodeURI(uri);
console.log(encoded);
// expected output: "https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"

try {
    
    
  console.log(decodeURI(encoded));
  // expected output: "https://mozilla.org/?x=шеллы"
} catch (e) {
    
     // catches a malformed URI
  console.error(e);
}

Guess you like

Origin blog.csdn.net/qq_45890970/article/details/123629061