【Front-end】JavaScript

AcWing Web Application Course (y total yyds)
just study the following cases carefully:

1. How to change the values ​​in the input and output boxes?

Insert image description here
Insert image description here

2. Several examples

Enter two numbers and calculate the sum of the two numbers.

let input=document.querySelector(".input");
let run=document.querySelector("button")
let output=document.querySelector(".output");


function main(){
    
    
     run.addEventListener("click",function(){
    
    
        let [a,b]=input.value.split(' ');
        a=parseInt(a);
        b=parseInt(b);
        output.innerHTML=a+b;
     });
}

export{
    
    
    main
}

Enter a decimal and return the result rounded toward zero.

let input=document.querySelector(".input");
let run=document.querySelector("button")
let output=document.querySelector(".output");


function main(){
    
    
     run.addEventListener("click",function(){
    
    
        let x=parseFloat(input.value);
        output.innerHTML=parseInt(x);
     });
}

export{
    
    
    main
}


Input a, b, c and output the value of (a + b) * c.

let input=document.querySelector(".input");
let run=document.querySelector("button")
let output=document.querySelector(".output");


function main(){
    
    
     run.addEventListener("click",function(){
    
    
        let [a,b,c]=input.value.split(' ');
        a=parseFloat(a);
        b=parseFloat(b);
        c=parseFloat(c);
        output.innerHTML=(a+b)*c;
     });
}

export{
    
    
    main
}

Output is the following diamond shape.

let input=document.querySelector(".input");
let run=document.querySelector("button")
let output=document.querySelector(".output");


function main(){
    
    
     let s="";
     s+="  *\n"
     s+=" ***\n"
     s+="*****\n"
     s+=" ***\n"
     s+="  *\n"
     output.innerHTML=s;
}

export{
    
    
    main
}


3. JS classes and objects

Take the Point class and ColorPoint class as an example:

class Point{
    
    
    constructor(x,y){
    
    
        this.x=x;
        this.y=y;
        Point.cnt++;
    }

    init(){
    
    
        this.sum=this.x+this.y;// 成员变量可以在任意的成员方法中定义
    }

    toString(){
    
    
      //  return '('+this.x+','+this.y+')';
      return `(${
      
      this.x},${
      
      this.y})`; //格式化写法
    }

    static print_class_name(){
    
     //定义静态方法
        console.log("Point");
    }

}

class ColorPoint extends Point{
    
    
    constructor(x,y,color){
    
    
        super(x,y);//初始化父类
        this.color=color;
    }

    toString(){
    
    
        return `${
      
      this.color} ${
      
      super.toString()}`
    }
}

Point.cnt=0;//定义静态变量

let main=function(){
    
    
    let p=new Point(3,4);
    p.init();
    console.log(p.sum);
    console.log(p.toString());
    ColorPoint.print_class_name();//静态成员方法可以被继承
    console.log(ColorPoint.cnt)//静态成员变量也可以被子类调用
}

4. Events in JS

JS code is generally triggered through events

4.1 Mouse related events

eg.

let div=document.querySelector('div');//获取div标签
let main= function(){
    
    
    div.addEventListener('click',function(event){
    
     //在获取的div标签上增加事件监听器,当发生click事件时,触发定义的函数。 其中event是绑定的一个参数。
        console.log(event);
        console.log(event.type);
    });
    

}

export{
    
    
    main
}

After clicking on the div, the complete event printed out is like this:
Insert image description here
Insert image description here
Various information about this mouse click can be recorded. The specific meaning can be checked in the document when using it.
Other trigger events:
click: left mouse button click
dblclick: left mouse button double click
contextmenu: right mouse button click
mousedown: mouse press, including left button, scroll wheel, right button
event.button: 0 means left button, 1 means middle button, 2 means Right
mouseup: Mouse up, including left button, scroll wheel, right button
event.button: 0 means left button, 1 means middle button, 2 means right button

4.2 Keyboard-related events

keydown、keyup、keypress

    input.addEventListener('keydown',function(event){
    
    
        console.log(event.type,event.code)
    });

Insert image description here

4.3 Form related events

focus: Focus
blur: Unfocus
change: The content of the element changes

    input.addEventListener('focus',function(event){
    
    
        console.log(event.type,event.code)
    });
    input.addEventListener('blur',function(event){
    
    
        console.log(event.type,event.code)
    });

Insert image description here

4.4 Window related events

resize: Triggered by page size change
scroll: Triggered by scrolling
load: Triggered after all resources in the page have been loaded

    window.addEventListener("resize",function(e){
    
    
        console.log(e.type);

    });

5. Common JS libraries

y General learning principle: As long as you understand these things, then check them while writing

5.1 jQuery

5.1.1 Use

Just <head>add it to the element ; or download it from the official website<script src="https://cdn.acwing.com/static/jquery/js/jquery-3.3.1.min.js"></script>


let main=function(){
    
    
    let $div=$('div');
    console.log($div);

    $div.on("click",function(){
    
    
        console.log("click div");
        $div.off("click");//解绑 使这个div只能被点击一次
    });

};


export{
    
    
    main
}

5.1.2 Click events can be distinguished by name

let main=function(){
    
    
    let $div=$('div');
    console.log($div);

    $div.on("click.name1",function(){
    
    
        console.log("click div 1");
        $div.off("click.name1");//解绑 使这个div只能被点击一次
    });

    $div.on("click.name2",function(){
    
    
        console.log("click div 2");
    });


};


export{
    
    
    main
}

Insert image description here

5.1.3 Preventing events from being passed upward

For the following code:

    <div>
        <a href="http://www.acwing.com" target="_blank">AcWing</a>
    </div>

Clicking on the a tag not only triggers the event on the a tag, but also triggers the event on the div tag (passed upward)

let main=function(){
    
    
    let $div=$('div');
    console.log($div);

    $div.on("click",function(){
    
    
        console.log("click div 1");
    });

    $('a').on('click',function(e){
    
    
        console.log("click link");
        e.stopPropagation(); //阻止事件向上传递,div的事件没有被触发
     //   e.preventDefault();//阻止当前事件发生
     // return false; 可以直接操作以下两个函数
    });



};


export{
    
    
    main
}

5.1.4 Hiding and showing elements

Insert image description here


let main=function(){
    
    
    let $div=$('div');
    let $btn_hidden=$('#btn-hidden');
    let $btn_show=$('#btn-show');

    $btn_hidden.on('click',function(){
    
    
        $div.hide(1000);
        //hideout 是淡入淡出
    });

    $btn_show.on('click',function(){
    
    
        $div.show();
    });
};

export{
    
    
    main
}

5.1.5 Element addition, deletion, etc.

Insert image description here

5.1.6 Operations on classes

You can add a class my-div to the div tag
Insert image description here

5.1.7 Operations on css

$("div").css("background-color")//获取某个CSS的属性
$("div").css("background-color","yellow")//设置某个CSS的属性
$('div').css({
    
    
    width: "200px",
    height: "200px",
    "background-color": "orange",
});

5.1.8 Operations on label attributes

$('div').attr('id')//获取属性
$('div').attr('id', 'ID')//设置属性

5.1.9 Operations on HTML content and text

$A.html() // 获取、修改HTML内容
$A.text() // 获取、修改文本信息
$A.val()  // 获取、修改文本的值 一般是获取input、textarea里面的内容

5.1.10 Search

Insert image description here

AJAX:
Do not refresh the page, only get some data from the server, usually some Json data

The get method
url is the link called by the backend, and
the data can be passed to the dictionary.
Success means: if no error is reported, get the information (resp) from the backend, call this function, and parse the backend information.

$.ajax({
    
    
    url: url,
    type: "GET",
    data: {
    
    
    },
    dataType: "json",
    success: function (resp) {
    
    

    },
});

5.2 setTimeout and setInterval

setTimeout(func, delay) executes the function x seconds after the event occurs
setInterval(func, delay) executes the function every x seconds

clearTimeout() closes the timer
clearInterval() closes the function that is executed periodically

the difference:
Insert image description here

5.3 requestAnimationFrame(func)

requestAnimationFrame(func)
This function will be executed once before the browser refreshes the page next time. It is usually written recursively to execute the func function 60 times per second. When calling, a parameter will be passed in, indicating the timestamp of function execution, in milliseconds.
This function can be used for animation


let main=function(){
    
    
    let step=function(){
    
    
        let $div=$('div').width($('div').width()+1);
        requestAnimationFrame(step);
    };

    // for(let i=0;i<100;i++){
    
    
    //     step();
    // }

    requestAnimationFrame(step);



};

export{
    
    
    main
}

Stop on mouse click:

let func_id;

let main=function(){
    
    
    let step=function(timestamp){
    
    
        let $div=$('div').width($('div').width()+1);
        if(timestamp/1000<=10){
    
    
            func_id= requestAnimationFrame(step);//递归执行
        } //限制执行时长
        
    };

    //调用该函数
    func_id= requestAnimationFrame(step);

    $('div').on('click',function(){
    
    
        cancelAnimationFrame(func_id);
    });
};


export{
    
    
    main
}

5.4 Map、Set、localStorage

localStorage: exists in the user's browser and remains unchanged regardless of whether it is refreshed or not. User preferences and the like can be stored locally.


let map=new Map();
map.set('kk',18);
console.log(map.get('kk'));//若没有,返回undefined

let set=new Set();
set.add(1);
set.add(()=>{
    
    
    console.log("hello");
}); //插入函数也没有问题

localStorage.setItem('name','zjx');


Insert image description here

Guess you like

Origin blog.csdn.net/qq_39679772/article/details/126301963