The book reading experience of WEB APLS

Web APIs

Basic understanding of Web API

Function and classification

  • Function: Use JS to operate html and browser
  • Category: DOM (Document Object Model), BOM (Browser Object Model)

DOM (Document Object Model)

DOM (Document Object Model) is an API used to render and interact with any HTML or XML document

Vernacular: DOM is a set of functions provided by the browser specifically for manipulating web content.

DOM tree

What is a DOM tree

  • Visually represent HTML documents in a tree structure, which we call a document tree or DOM tree.
  • Nouns describing the relationship between web page content
  • Function: The document tree intuitively reflects the relationship between tags

Please add image description

DOM object

DOM object: JS object generated by the browser based on html tags

  • All label properties can be found on this object
  • Modifying the properties of this object will automatically be mapped to the label.

The core idea of ​​DOM

  • Treat web content as objects

document object

  • It is an object provided in the DOM
  • Therefore, the properties and methods it provides are used to access and operate web content.
    • Example: document.write()
  • All content of the web page is in the document

Get DOM object

Get DOM elements based on css selector (emphasis)

Select the first element that matches

grammar:

document.querySelector('css选择器')

parameter:

Contains one or more valid css selector strings

return value:

The first element matched by the css selector is an HTMLElement object.

If no match is found, null is returned.

Select matching multiple elements

grammar

document.querySelector('css选择器')

parameter:

Contains one or more valid css selector strings

return value:

Collection of NodeList objects matched by css selector

document.querySelectorAll('ul li')

The querySelector() method can directly operate and modify

The querySelectorAll() method cannot be modified directly. It can only modify the elements inside through traversal.

document.querySelectorAll('css选择器')

What you get is a pseudo array:

  • Array with length and index number
  • But there are no array methods such as pop() push()
  • If you want to get each object inside, you need to traverse (for) to obtain it.

Notice:

  • Even if there is only one element, what is obtained through querySelectAll() is a pseudo array with only one element in it.

Other ways to get DOM elements

// 根据id获取一个元素
document.getElementById('nav')
// 根据标签获取一个元素 获取页面  所有div
document.getElementsByTagName('div')
// 根据类获取一个元素 获取页面  所有类为w的元素
document.getElementsByClassName('w')

Set/modify DOM element content

  1. document.write()

    • Text content can only be appended to the previous position

    • document.write('<h3> 你好,世界! </h3>')
      
    • Tags contained in the text will be parsed

  2. Element.innerText property

    • Add/update text content to any label position text
    • Containing tags will not be parsed
  3. Element .innerHTML attribute

    • Recommend/update text content to any label position
    • Tags contained in the text will be parsed
// innerHTML 属性
 box.innerHTML = '<h3>前端程序员<br>的头发都很多</h3>'

The difference between the three

  • The document.write() method can only be appended to the body
  • The element's .innerText attribute only identifies content and cannot parse tags
  • Element .innerHTML attribute - Ability to parse tags
  • If you are still wondering which one to use, you can choose innerHTML

The randomly selected names of the cases are displayed inside the specified label.

Requirement: Put the name inside the span box

analyze:

  1. Get span element
  2. get random names
  3. Write the name inside the element through innerText or innerHTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
      
      
            display: inline-block;
            width: 150px;
            height: 30px;
            border: 1px solid pink;
            vertical-align: middle;
            line-height: 30px;
            
        }
    </style>
</head>
<body>
    抽中的选手:<div></div>
    <script>
        // 1.获取元素
        let box = document.querySelector('div')
        // 2.得到随机名字
        // 随机数
        function getRandom(min,max) {
      
      
            return Math.floor(Math.random() * ( max - min +1 )) +min
        }
        // 声明一个数组
        let arr = ['小米','小吗','小是','小的','小发',
        '小人','小他','小哦','小明']

        // 生成一个随机数  作为数组的索引号
        let random = getRandom(0,arr.length - 1)
        // document.write(arr[random])

        //3. 写入标签内部
        box.innerHTML = arr[random]

        // 之后删除这个名字
        arr.splice(random,1 )
        console.log(arr);
    </script>
</body>
</html>

An error occurred in the middle and the js was written to the div, resulting in the random name not being displayed.

Set/modify DOM element attributes

Common properties

You can also set/modify the style attributes of tag elements through JS, such as changing images through src.

The most common attributes are: href, title.src, etc.

grammar:

对象.属性 =//1.获取元素
let pic = document.querySelector('img')
//2.操作元素
pic.src = './images/b02.jpg'
pic.title = '这是一个图片'

Case

Requirement: When we refresh the page, the pictures on the page randomly display different pictures

analyze:

  • To display randomly, you need to use the random function
  • To change the image, you need to use the src attribute of the image to modify it.

Core idea:

  • Get image elements
  • Randomly get the picture serial number
  • Picture.src = picture random path
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img {
      
      
            width: 500px;
            height: 300px;
        }
    </style>
</head>
<body>
    <img src="../10327.gif" alt="#">
    <!-- <img src="../案例/小学期/images/book1.png" alt=""> -->

    <script>
        //1. 获取图片元素
        let pic  =document.querySelector('img')
        //2. 随机得到图片序号
        function getRandom(min,max) {
      
      
            return Math.floor(Math.random() * ( max - min +1 )) +min
        }
        let num = getRandom(1,6)
        //3. 完成src  属性赋值
        pic.src = `../案例/小学期/images/book${ 
        num}.png`
    </script>
</body>
</html>

style properties

You can also set/modify the style attributes of label elements through JS.

  • For example, the color style can be automatically changed through carousel dots.
  • Click the button to scroll the image. This is the position of the moved image left and so on.

Learning path:

  1. Manipulate CSS through the style attribute
  2. Operation class name (className) operation cSs3.Control CSS through classList manipulation classes
  3. Control CSS through classList manipulation classes
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
      
      
            width: 300px;
            height: 300px;
            background-color: pink;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        //1.获取元素
        let box = document.querySelector('div')
        //2.改变1背景颜色  样式 style
        box.style.background = 'hotpink'
        box.style.width = '400px'
        box.style.marginTop = '100px'

    </script>
</body>
</html>

Notice:

  • Modify the style through the style attribute
  • If the attribute has a - connector, it needs to be converted to camel case (marginTop)
  • When assigning values, don’t forget to add css units when needed.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
      
      
            background-image: url(../案例/xtx/images/sprites.png);
        }
    </style>
</head>
<body>
    <script>
        function getRandom(min,max) {
      
      
            return Math.floor(Math.random() * ( max - min +1 )) +min
        }

        // 随机的值1-10
        let num = getRandom(1,10)

        // 修改背景图片
        document.body.style.backgroundImage = `url(../aadada/ada${ 
        num}.jpg )`
        // 图片路径
    </script>
</body>
</html>

2. Manipulate class name (className) and manipulate CSS

If there are many styles to be modified, it would be cumbersome to modify them directly through the style attribute. We can use the CSS class name.

grammar:

//active是一个css类名
元素.className = 'active'

Notice:

  1. Since class is a keyword, use className instead.
  2. className replaces the old value with the new value. If you need to add a class, you need to keep the previous class name.

3. Control CSS through classList operation class

In order to solve the problem that className easily overwrites the previous class name, we can append and delete class names through classList.

grammar:

//追加一个类
元素.classList.add('类名')
//删除一个类
元素.classList.remove('类名')
//切换一个类
元素.classList.toggle('类名')

form element properties

In many cases, the properties of a form also need to be modified. For example, if you click on the eye, you can see the password. The essence is to convert the form type into a text box. It has normal attributes and values ​​and is no different from other label attributes.

Get: DOM object.Attribute name

set password

Settings: DOM object.property name=new value

表单.value = '用户名'
表单.type = 'password'

Adding a form attribute has an effect, removing it has no effect. Always use a Boolean value to indicate that if it is true, it means that the attribute has been added; if it is false, it means that the attribute has been removed.

For example: disabled, checked, selected

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" value="请输入">
    <button disabled>按钮</button>
    <input type="checkbox" id="check">
    <script>
        //1.获取元素
        let input = document.querySelector('input')
        //2.取值或者设置值   得到input里面的值可以用value
        console.log(input.value)
        input.value = '小米手机'
        input.type = 'password'

        //2.启用按钮
        let button = document.querySelector('button')
        button.disabled = false
        // false启用按钮,ture关闭按钮


        //勾选复选框
        let checkbox = document.querySelector('.check')
        checkbox.checked = false

    </script>
</body>
</html>

Timer-intermittent function

Start timer

setInterval(函数,间歇时间)

Function: Call this function every once in a while

The interval unit is milliseconds

function repeat() {
    
    
    console.log('ajdahdajdpajpo')
}
//每间隔一秒调用repeat函数
srtInterval(repeat,1000)

Notice:

  1. Function names do not need parentheses

  2. The timer returns an id number

off timer

let 变量名 = setInterval(函数,间歇时间)
clearINterval(变量名)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        setInterval(function() {
      
      
            console.log('高新就业');
        },1000)

        function show() {
      
      
            console.log('月薪过万');
        }

        setInterval(show,1000)


        // 清除定时器
        clearInterval(cheakbox)
    </script>
</body>
</html>

Case

Countdown effect

Requirement: The button can be used after 60 seconds

analyze:

  1. Start by disabling the button (disabled attribute)
  2. Must get the element
  3. Processing logic within functions
    • Seconds start to decrease
    • The text inside the button changes accordingly
    • If the seconds is equal to 0, the text inside the stop timer changes to Agree and the last button can be clicked.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .btn{
      
      
        margin-left: 30px;
    }
</style>
<body>
    <textarea name="" id="" cols="30" rows="10">
        用户注册协议
        欢迎注册成为京东用户!在您注册过程中,您需要完成我们的注册流程【请您注意】
        如果您不同意以下协议全部或任何条款约定,请您停止注;
    </textarea>
    <br>
    <button class="btn" disabled>我已经阅读用户协议(3)</button>
    <script>
        //1.获取元素
        let btn = document.querySelector('.btn')
        //2.计算逻辑
        //2.1需要一个变量,用来计数
        let i = 3
        //2.2 开启定时器   简歇一秒
        let timer = setInterval(function() {
      
      
            i--
            // console.log(i);
            btn.innerHTML = `我已经阅读用户协议(${ 
        i})`
            if (i === 0) {
      
      
                // 不走了,清除定时器
                clearInterval(timer)
                //开启按钮
                btn.disabled = false
                //更换文字
                btn.innerHTML = '我已经阅读用户协议'
            }
        },1000)

    </script>
</body>
</html>

Web page carousel

Requirement: Switch a picture every second

analyze:

  1. Get elements (pictures and text)
  2. Set timer function
    • Set a variable++
    • Change the number of pictures
    • Change text message
  3. Process pictures and automatically restore them to play from the beginning
    • If the picture is played to the last one, it will be the 9th picture
    • then reset the variable to 0
    • Note that the logic code is written in front of the picture and text changes.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="img-box">
        <img src="../素材/images/b01.jpg" alt="">
        <div class="tip">
            <h3 class="text">挑战云歌单,欢迎你来</h3>
        </div>
    </div>
    <script>
         // 数据
         let data = [
            {
      
      
                imgSrc: '../素材/images/b01.jpg',
                title: '挑战云歌单,欢迎你来'
            },
            {
      
      
                imgSrc: '../素材/images/b02.jpg',
                title: '田园日记,上演上京记'
            },
            {
      
      
                imgSrc: '../素材/images/b03.jpg',
                title: '甜蜜攻势再次回归'
            },
            {
      
      
                imgSrc: '../素材/images/b04.jpg',
                title: '我为歌狂,生为歌王'
            },
            {
      
      
                imgSrc: '../素材/images/b05.jpg',
                title: '年度校园主题活动'
            },
            {
      
      
                imgSrc: '../素材/images/b06.jpg',
                title: 'pink老师新歌发布,5月10号正式推出'
            },
            {
      
      
                imgSrc: '../素材/images/b07.jpg',
                title: '动力火车来到西安'
            },
            {
      
      
                imgSrc: '../素材/images/b08.jpg',
                title: '钢铁侠3,英雄镇东风'
            },
            {
      
      
                imgSrc: '../素材/images/b09.jpg',
                title: '我用整颗心来等你'
            },
        ]

        //1.获取元素(图片和文字)
        let pic  = document.querySelector('.pic')
        let text  = document.querySelector('.text')
        let i = 0
        // 开定时器
        setInterval(function(){
      
      
            i++
            //修改src属性
            pic.src = data[i].imgSrc
            text.innerHTML = data[i].title

            //衔接
            if(i === data.length - 1){
      
      
                i= -1
                //用-1是因为代码运行到上面就1要++,
                // 使用用-1.然后++之后刚好为0
                //  i === 8? i = -1 : i
            }
        },1000)
    </script>
</body>
</html>

event

event listening

  • Events are actions or things that happen within the system while programming

    • For example, a user clicks a button on a web page
  • event listening

    • It is to let the program detect whether an event occurs. Once an event is triggered, it immediately calls a function to respond, also known as registering an event.
  • grammar

元素.addEVentListener('事件',要执行的函数)
//事件必须是字符串
  • Three elements of event monitoring:
    • Event source: The DOM element was triggered by the event. To obtain the DOM element
    • Event: How to trigger it, such as mouse click, mouse over, etc.
    • Function called by event: what to do
//获取元素
let btn = document.querySelector('button')
//事件监听(注册事件)
btn.addEventListener('click',function() {
    
    
    alert('被点击了')
})

Notice:

  1. Event type should be enclosed in quotes
  2. The function is executed after clicking. It will be executed once every time you click.

event type

event content Attributes
mouse events Mouse trigger click mouse click
mouseenter mouse passes
mouseleave mouse leaves
focus event Form gets cursor focus gets focus
blur loses focus
Keyboard events keyboard trigger keydown triggers when the keyboard is pressed
keyup triggers when the keyboard is raised
text event Form input trigger input user input trigger

Case

higher order function

High-order functions can be simply understood as advanced applications of functions. Functions in JavaScript can be treated as [values]. Based on this feature, advanced applications of functions can be realized.

[Value] is data in JavaScript, such as numerical values, strings, Boolean, objects, etc.

Callback

If function A is passed as a parameter to function B, we call function A a callback function.

Simple understanding: When a function is passed as a parameter to another function, this function is a callback function.

Common usage scenarios

function fn() {
    
    
    cinsole.log('我是回调函数。。。')
}
setInterval(fn,1000)

environment object

The environment object refers to the special variable this inside the function, which represents the environment in which the current function is running.

Function: clarifying the point of this can make our code more concise

  • The method of calling the function is different, and the object referred to by this is also different.
  • [Whoever calls, this is who] is a rough rule for judging where this points.
  • Calling the function directly is actually equivalent to the window. function, so this refers to window.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>点击</button>
    <script>
        // 环境对象 this 他就是个对象
        function fn() {
      
      
            console.log(this);
        }
        fn()


        let btn = document.querySelector('button')
        btn.addEventListener('click',function() {
      
      
            console.log(typeof this);
        })

        //因为btn调用了这个函数,所以this指向谁
    </script>
</body>
</html>

Exclusionary thinking

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .pink{
      
      
            background-color: pink;
        }
    </style>
</head>
<body>
    <button class="pink">1</button><button>2</button>
    <button>3</button><button>4</button>


    <script>
        let btns = document.querySelectorAll('button')
        for(let i = 0; i< btns.length; i++) {
      
      
            btns[i].addEventListener('click',function(){
      
      
                // this.classList.add('pink')
                // 干掉所有人
                // for(let j = 0; j < btns.length; j++) {
      
      
                //     btns[j].classList.remove('pink')
                    
                // }


                // 我只需要找出那个唯一的pink类,删除
                document.querySelector('.pink').classList.remove('pink')
                // 复活我自己
                this.classList.add('pink')


                
            })
        }
    </script>
</body>
</html>

Node operations

DOM node

  • DOM node
    • Each content in the DOM tree is called a node node type.
  • element node
    • All tags such as body.div
    • html is the root node
  • attribute node
    • All attributes such as href
  • text node
    • All text other
  • other

Find node

Node relationship:

parent node

child node

Sibling node

Parent node search
  • parentNode attribute
  • Returns the nearest parent node. If not found, null is returned.
子元素.parentNode
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="father">
        <div class="son">儿子</div>
    </div>
    <script>
        let son = document.querySelector('.son')
        // 找爸爸   属性
        // console.log(son.parentNode)
        son.parentNode.style.dispaly = 'none'
    </script>
</body>
</html>

Child node search

childNodes

  • Get all child nodes, including text nodes (spaces, newlines), comment nodes, etc.

children (emphasis)

  • Get only all element nodes
  • What is returned is still a pseudo array
父元素.children
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>点击</button>
    <ul>
        <li>我是孩子</li>
        <li>我是孩子</li>
        <li>我是孩子</li>
        <li>我是孩子</li>
        <li>我是孩子</li>
        <li>我是孩子</li>
    </ul>


    <script>
        let btn = document.querySelector('button')
        let ul = document.querySelector('ul')
        btn.addEventListener('click',function() {
      
      
            // console.log(ul.children)
            for (let i = 0;i < ul.children.length; i++){
      
      
                ul.children[i].style.color = 'red'
            }
        })
        ul.children[0].style.color = 'green'
    </script>
</body>
</html>
Sibling node search
  1. next sibling node
    • nextElementSiblingProperty
  2. Previous sibling node
    • previousElementSibling Property
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>点击</button>
    <ul>
        <li>第1个</li>
        <li class="two">第2个</li>
        <li>第3个</li>
        <li>第4个</li>
    </ul>
    <script>
        let btn = document.querySelector('button')
        let two = document.querySelector('.two')
        btn.addEventListener('click',function(){
      
      
            two.nextElementSibling.style.color = 'red'
            two.previousElementSibling.style.color = 'green'
        })
    </script>
</body>
</html>

Node operations

In many cases, we need to add elements to the page

  • For example, click the publish button to add a new message

Generally, when we add a new node, we do as follows:

  • Create a new node
  • Place the created new node inside the specified element
Create node

grammar:

document.createElement('标签名')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        
    </ul>
    <script>
        let div = document.createElement('div')
        // 追加属性
        div.className = 'current'
        let li = document.createElement('li')
    </script>
</body>
</html>
Append node
  • If you want to see it on the interface, you have to insert it into a parent element.
  • Insert into the last child element of the parent element
//插入到父元素的最后一个子元素
父元素.appendChild(子元素)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        
    </ul>
    <script>
        // let div = document.createElement('div')
        // 追加属性
        // div.className = 'current'
        let ul = document.querySelector('ul')
        let li = document.createElement('li')
        li.innerHTML = '我是li'

        ul.appendChild(li)

    </script>
</body>
</html>
  • Insert into the parent element before a child element
//插入到父元素中某个子元素前面
父元素.insertBefore(要出入的元素,在哪个元素前面)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li>我是孩子</li>
        <li class="two">two</li>
    </ul>
    <script>
        // let div = document.createElement('div')
        // 追加属性
        // div.className = 'current'
        let ul = document.querySelector('ul')
        let li = document.createElement('li')
        li.innerHTML = '我是li'
        // 2.追加节点 父元素.appendChild(子元素) 插入到父元素的最后一个子元素
        // ul.appendChild(li)
        // 3、追加节点 父元素.insertBefore(要出入的元素,在哪个元素前面)
        // ul.children[1]获取ul中第二个li
        ul.insertBefore(li,ul.children[1])


    </script>
</body>
</html>

Case

Requirements: Render page analysis based on data:

①: Prepare the empty ul structure

②: Create a new empty li based on the number of data

③: Add content img title, etc. in li

④:Add to ul

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>学成在线首页</title>
    <link rel="stylesheet" href="style.css">

</head>

<body>

    <!-- 4. box核心内容区域开始 -->
    <div class="box w">
        <div class="box-hd">
            <h3>精品推荐</h3>
            <a href="#">查看全部</a>
        </div>
        <div class="box-bd">
            <ul class="clearfix">
                <!-- <li>
                    <img src="./images/course01.png" alt="">
                    <h4>
                        Think PHP 5.0 博客系统实战项目演练
                    </h4>
                    <div class="info">
                        <span>高级</span> • <span> 1125</span>人在学习
                    </div>
                </li> -->
            </ul>
        </div>
    </div>
    <script>
        let data = [
            {
      
      
                src: 'images/course01.png',
                title: 'Think PHP 5.0 博客系统实战项目演练',
                num: 1125
            },
            {
      
      
                src: 'images/course02.png',
                title: 'Android 网络动态图片加载实战',
                num: 357
            },
            {
      
      
                src: 'images/course03.png',
                title: 'Angular2 大前端商城实战项目演练',
                num: 22250
            },
            {
      
      
                src: 'images/course04.png',
                title: 'Android APP 实战项目演练',
                num: 389
            },
            {
      
      
                src: 'images/course05.png',
                title: 'UGUI 源码深度分析案例',
                num: 124
            },
            {
      
      
                src: 'images/course06.png',
                title: 'Kami2首页界面切换效果实战演练',
                num: 432
            },
            {
      
      
                src: 'images/course07.png',
                title: 'UNITY 从入门到精通实战案例',
                num: 888
            },
            {
      
      
                src: 'images/course08.png',
                title: '我会变,你呢?',
                num: 590
            },
            {
      
      
                src: 'images/course08.png',
                title: '我会变,你呢?',
                num: 590
            }
        ]
        let ul = document.querySelector('ul')
        // 1. 根据数据的个数,决定这小li的个数
        for (let i = 0; i < data.length; i++) {
      
      
            // 2. 创建小li
            let li = document.createElement('li')
            // console.log(li)

            // 4. 先准备好内容,再追加 
            li.innerHTML = `
            <img src=${ 
        data[i].src} alt="">
            <h4>
                ${ 
        data[i].title}
            </h4>
            <div class="info">
                <span>高级</span> • <span> ${ 
        data[i].num}</span>人在学习
            </div>
            `
            // 3. 追加给ul   父元素.appendChild(子元素)
            ul.appendChild(li)

        }
    </script>
</body>

</html>
Clone node

Under special circumstances, we add a new node and follow the following operations:

Copy an original node

Place the copied node inside the specified element

//克隆一个已有的元素节点
元素.cloneNode(布尔值)

cloneNode will clone an element that is the same as the original tag, and pass in a boolean value in parentheses

  • If true, it means that descendant nodes will be cloned together when cloning.
  • If false, it means that descendant nodes are not included in the clone.
  • Default is false
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li>我是内容</li>
    </ul>
    <script>
        let ul = document.querySelector('ul')
        // 括号为空则,默认为false 若为false,则代表克隆时不包含后代节点
        let newul = ul.cloneNode(true)
        document.body.appendChild(newul)
    </script>
</body>
</html>
Delete node

If a node is no longer needed in the page, you can delete it

In JavaScript native DOM operations, to delete an element you must delete it through the parent element

grammar

父元素.removeChild(要删除的元素)

Note:
If there is no parent-child relationship, the deletion will not be successful.

There is a difference between deleting a node and hiding a node (display.none): the hidden node still exists, but if you delete it, the node will be deleted from the html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>点击</button>
    <ul>
        <li>我是内容</li>
    </ul>
    <script>
        let btn = document.querySelector('button')
        let ul =document.querySelector('ul')
        btn.addEventListener('click',function(){
      
      
            // 删除语法
            ul.removeChild(ul.children[0])
        })
    </script>
</body>
</html>

time object

Time object: an object used to represent time

Function: You can get the current system time

Instantiate

When the new keyword is found in the code, this operation is generally called instantiation.

Create a time object and get the time

Get current time

//获取当前时间
let date = new Date()

// 获取指定时间
let date = new Date('1949-10-09')

time object methods

Because the data returned by the time object cannot be used directly, it needs to be converted into a format commonly used in actual development.

method effect illustrate
getFullYear() Get year Get the four-digit year
getMonth() Get month The value is 0~11
getDate() Get every day of the month The values ​​are different in different months
getDay() Get day of the week The value is 0~6
getHours() Get hours The value is 0~23
getMinutes() Get minutes The value is 0~59
getSeconds() Get seconds The value is 0~59
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div></div>
    <script>
        let arr = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六']
        getTime()

        setInterval(getTime,1000)

        function getTime() {
      
      
            let date = new Date()
            let year = date.getFullYear()
            let month = date.getMonth() +1 
            let date1 = date.getDate()
            let day = date.getDay()
            let hour = date.getHours()
            let min = date.getMinutes()
            let sec = date.getSeconds()

            let div = document.querySelector('div')
            div.innerHTML = `今天是:${ 
        year}${ 
        month}${ 
        date1}${ 
        hour}:${ 
        min}:${ 
        sec} ${ 
        arr[day]}`
        }
    </script>
</body>
</html>

Timestamp

what is timestamp

It refers to the number of milliseconds from 00:00:00 on January 1, 1970 to the present. It is a special way of measuring time.

Three ways to get timestamp

 // 1.getTime()
let date = new Date()
console.log(date.getTime())
// 2.简写 + new Date()  (推荐)
console.log(+new Date());
// 3.使用Date.now()  只能得到当前的
console.log(Date.now());

Repaint and reflow (interview)

How the browser renders the interface

  • Parse (Parser) HTML and generate DOM Tree (DOM Tree)
  • Parse (Parser) css at the same time and generate style rules (Style Rules)
  • Generate a rendering tree (Render Tree) based on the DOM tree and style rules
  • Carry out layout (reflow/rearrangement): According to the generated rendering tree, obtain the geometric information (position, size) of the node, and use it in the layout (big box)
  • Painting (redrawing): Drawing the entire page based on calculations and acquired information
  • Display: displayed on the page

Redraw and reflow (reflow)

Reflow (rearrangement)

  • When the size, structure, layout, etc. of some or all elements in the Render Tree change, the browser will re-render part or all of the document, a process called reflow.

Redraw

  • Since the change of the style of a node (element) does not affect its position in the document flow and document layout (such as color, background-color, outline, etc.), it is called redrawing.

Redrawing does not necessarily cause reflow, but reflowing always causes redrawing. (Interview focus)

  • Operations that will cause reflow (reflow):
    • The first refresh of the page
    • The browser window size changes
    • The size or position of the element changes
    • Change the font size
      and content (such as: input box input, picture size)
    • Activate css pseudo-classes (eg: :hover)
    • Script to manipulate DOM (add or remove visible DOM elements)
  • Simply understand that if it affects the layout, there will be reflow.

event object

Get event object

What is the event object

  • It is also an object. This object contains relevant information when the event is triggered.
  • For example: in a mouse click event, the event object stores information such as where the mouse point is.

How to get

  • The first parameter of the event-bound callback function is the event object.
  • Generally named event, ev.e
元素.addEventListener('click',function(e) {
    
    }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>点击</button>
    <script>
        let btn = document.querySelector('button')
        btn.addEventListener('mouseenter',function(e) {
      
      
            console.log(e);
        })
    </script>
</body>
</html>

cursor

Some common attributes

  • type
    • Get the current event type
  • clientX/clientY
    • Gets the position of the cursor relative to the upper left corner of the browser's visible window
  • offsetX/offsetY
    • Gets the position of the cursor relative to the upper left corner of the current DOM element
  • key
    • The value of the keyboard key pressed by the user
    • The use of keycode is now discouraged
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        document.addEventListener('mousemove',function(e){
      
      
            // console.log(11);
            // pageX 和 pageY 跟文档坐标有关系
            // console.log(e);
            console.log('clinetx:' + e.clientX,'clientY:' + e.clientY)
            console.log('pageX:' + e.pageX,'pageY:' + e.pageY)
            console.log('offsetx:' + e.offsetX,'offsetY:' + e.offsetY)
        })
    </script>
</body>
</html>

Case

The picture follows the mouse

Analysis:
①: The mouse moves on the page, using the mousemove event
②: Constantly assign the coordinate position of the mouse on the page to the left and top values ​​​​of the image

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img{
      
      
           position: absolute ; /*定位 */
           top: 0;
           left: 0;

        }
    </style>
</head>
<body>
    <img src="./tianshi.gif" alt="">
    <script>
        let pic = document.querySelector('img')
        document.addEventListener('mousemove',function(e) {
      
      
            // 不断获取当前鼠标坐标
            console.log(e.pageX)
            console.log(e.pageY)
            //把坐标给图片
            pic.style.left = e.pageX -40 + 'px'
            pic.style.top = e.pageY - 40 + 'px'
        })
    </script>
</body>
</html>

Press Enter to post on Weibo

Requirement: Press the Enter keyboard to publish information

Requirement 1: Detect the number of words entered by the user

  1. Register input event

  2. Assign the length of the text content to the corresponding value

  3. The maxlength attribute of the form can be directly limited to 200 numbers.

Requirement 2: The input cannot be empty

  • Determine if the content is empty, the prompt cannot be empty, and the direct return cannot be empty
  • To prevent meaningless spaces from being entered, use string.trim() to remove leading and trailing spaces.
  • and set the value of the form to an empty string
  • At the same time, the red color below is set to 0

Requirement 3: Add a new message

  • Create a small li, and then append data through innerHTML
  • Randomly obtain the contents of the data array, replace the picture and name of newNode and the message content
  • Use time objects to dynamize time new Date().toLocaleString()
  • append to ul

event stream

Event flow refers to the flow path during the complete execution of an event

  • Note: Assume there is a div in the page. When an event is triggered, it will go through two stages, namely the capture stage and the bubbling stage.
  • To put it simply: the capture phase is from parent to child and the bubbling phase is from child to parent

Event bubbling

Event bubbling concept:

When an event is triggered on an element, the same event will be triggered in turn on all ancestor elements of the element. This process is called event bubbling

Simple understanding: when an element triggers an event, the same-named events of all parent elements will be called upwards in sequence.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
      
      
            margin: 100px auto;
            width: 400px;
            height: 400px;
            background-color: pink;
        }


        .son {
      
      
            margin: 100px auto;
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <script>
        let fa = document.querySelector('.father')
        let son = document.querySelector('.son')

        fa.addEventListener('click', function() {
      
      
            alert('我是爸爸')
        })

        son.addEventListener('click', function() {
      
      
            alert('我是儿子')
        })
    </script>
</body>
</html>

event capture

Event capture concept:

Start from the root element of the DOM to execute the corresponding event (from outside to inside)

Event capture requires writing corresponding code to see the effect.

code

son.addEventListener(事件类型,事件处理函数,是否使用捕获机制)

illustrate:

  • The third parameter of addEventListener is passed in true to indicate that the capture phase is triggered (rarely used)
  • If false is passed in, it means the bubbling phase is triggered. The default is false.
  • If you use LO event monitoring, there is only the bubbling phase and no capture.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
      
      
            margin: 100px auto;
            width: 400px;
            height: 400px;
            background-color: pink;
        }


        .son {
      
      
            margin: 100px auto;
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <script>
        let fa = document.querySelector('.father')
        let son = document.querySelector('.son')

        fa.addEventListener('click', function() {
      
      
            alert('我是爸爸')
        },true)

        son.addEventListener('click', function() {
      
      
            alert('我是儿子')
        },ture)
    </script>
</body>
</html>

Block the flow of events

Because the bubble mode exists by default, it is easy for events to affect parent elements.

If you want to limit the event to the current element, you need to prevent the flow of events

To prevent the flow of events, you need to get the event object

grammar:

事件对象.stopPropagation()

This method can block the flow and propagation of events. It is not only effective in the bubbling stage, but also in the capturing stage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
      
      
            margin: 100px auto;
            width: 400px;
            height: 400px;
            background-color: pink;
        }


        .son {
      
      
            margin: 100px auto;
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <script>
        let fa = document.querySelector('.father')
        let son = document.querySelector('.son')

        fa.addEventListener('click', function() {
      
      
            alert('我是爸爸')
        })

        son.addEventListener('click', function(e) {
      
      
            alert('我是儿子')
            // 阻止事件流动
            e.stopPropagation()
        })
    </script>
</body>
</html>

Mouse over event:

mouseover and mouseout will have a bubbling effect

mouseenter and mouseleave have no bubbling effect (recommended)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
      
      
            margin: 100px auto;
            width: 400px;
            height: 400px;
            background-color: pink;
        }


        .son {
      
      
            margin: 100px auto;
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <script>
        let fa = document.querySelector('.father')
        let son = document.querySelector('.son')
        fa.addEventListener('mouseenter',function() {
      
      
            console.log(111);
        })

        fa.addEventListener('click', function() {
      
      
            alert('我是爸爸')
        })

        son.addEventListener('click', function(e) {
      
      
            alert('我是儿子')
            // 阻止事件流动
            e.stopPropagation()
        })
    </script>
</body>
</html>

Prevent default behaviors, such as link clicks not jumping and form fields jumping

grammar:

e.preventDefault()
  • The difference between the two registration events:
  • Traditional gn registration (LO)
    • For the same object, events registered later will overwrite previously registered events (the same event).
    • You can unbind the event by directly overwriting it with null.
    • They are all executed in the bubbling phase.
  • Event listening registration (L2)
    • Syntax: addEventListener(event type, event handling function, whether to use capture)
    • Events registered later will not overwrite previously registered events (the same event)
    • You can use the third parameter to determine whether it is executed in the bubbling or capturing phase.
    • You must use removeEventListener (event type, event handling function, capture or bubbling phase)
    • Anonymous functions cannot be unbound

event delegation

Event delegation is a knowledge and skill that uses the characteristics of event streams to solve some development needs.

Summarize:

  • Advantages: Add events to parent elements (can improve performance)
  • Principle: Event delegation actually uses the characteristics of event bubbling to add events to parent elements, and child elements can trigger them.
  • Implementation: event object.target can get the element that actually triggered the event
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li>我是第一个小li</li>
        <li>我是第二个小li</li>
        <li>我是第三个小li</li>
        <li>我是第四个小li</li>
        <li>我是第五个小li</li>
    </ul>
    <script>
        //不要每个小Li注册事件了而是把事件委托给他的爸爸
        // 事件委托是给父级添加事件而不是孩子添加事件
        let ul = document.querySelector('ul')
        ul.addEventListener('click',function(e) {
      
      
            // alert('我点击了')
            // 得到当前元素
            // console.log(e.target)
            e.target.style.color = 'red'
        })
    </script>
</body>
</html>

accordion effect

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        ul {
      
      
      list-style: none;
    }

    * {
      
      
      margin: 0;
      padding: 0;
    }

    div {
      
      
      width: 1200px;
      height: 400px;
      margin: 50px auto;
      border: 1px solid red;
      overflow: hidden;
    }

    div li {
      
      
      width: 240px;
      height: 400px;
      float: left;
      /* 过渡 */
      transition: all 500ms;
    }

    div ul {
      
      
      width: 1200px;
    }
    </style>
</head>
<body>
    <div id="box">
        <ul>
            <li>
                <a href="#">
                    <img src='../手风琴images/1.jpg' alt="">
                </a>
            </li>
            <li>
                <a href="#">
                    <img src='../手风琴images/2.jpg' alt="">
                </a>
            </li>
            <li>
                <a href="#">
                    <img src='../手风琴images/3.jpg' alt="">
                </a>
            </li>
            <li>
                <a href="#">
                    <img src='../手风琴images/4.jpg' alt="">
                </a>
            </li>
            <li>
                <a href="#">
                    <img src="../手风琴images/5.jpg" alt="">
                </a>
            </li>
        </ul>
    </div>


    <script>
        // 1.li默认有个宽度是240像素
        // 2.当我们鼠标经过,当前的小i 宽度变大 800px其余的小Li 变为100px
        // 3.·鼠标离开事件,所有的小Li都要复原宽度为240px
        // (1)获取元素
        let lis = document.querySelectorAll('li')
        // (2)绑定鼠标经过和离开事件
        for (let i = 0; i < lis.length; i++) {
      
      
            // 鼠标经过事件
            lis[i].addEventListener('mouseenter',function() {
      
      
                // 排他思想干掉所有人108px,复活我自己800px
                for ( j = 0; j < lis.length; j++) {
      
      
                    lis[j].style.width = '100px'
                }
                this.style.width = "800px"
            })
            // 鼠标离开
            lis[i].addEventListener('mouseleave',function() {
      
      
                // 排他思想干掉所有人108px,复活我自己800px
                for ( j = 0; j < lis.length; j++) {
      
      
                    lis[j].style.width = '240px'
                }
            })
        }
    </script>
</body>
</html>

list is not defined at HTMLLIElement.

This error occurred during this period because I wrote lis.length in the loop to change all widths to 100px as list.length.

scroll and load events

scroll event

  • Event triggered when the page is scrolled
  • Why study?
    • Many web pages need to detect when the user scrolls the page to a certain area and do some processing, such as fixing the navigation bar, such as returning to the top.
  • Event name: scroll
  • Listen to the entire page scroll:
window.addEventListener('scroll',function(){
})

Add scroll event to window or document

  • To monitor the internal scrolling of an element, just add it to an element directly.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
      
      
            height: 3000px;
        }
        div{
      
      
            overflow:auto ;
            width: 200px;
            height: 50px;
            background-color: pink;
        }
    </style>
</head>
<body>
    <div>
        文字
        文字
        文字
        文字
        文字
        文字
        文字

        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字
        文字

        文字
        文字
        文字
        文字
        文字

    </div>
    <script>
        let div = document.querySelector('div')
        // window.addEventListener('scroll',function(){
      
      
        //     console.log(111);
        // })
        div.addEventListener('scroll',function(){
      
      
            console.log(111)
        })
    </script>
</body>
</html>

loading event

Event triggered when external resources (such as images, external CSS and JavaScript, etc.) are loaded.

Why study?

  • Sometimes you need to wait for all page resources to be processed to do something
  • Old codes like to write scripts in the head. At this time, if you directly look for the DOM element, you can't find it.

Event name: load

All resources on the monitoring page have been loaded:

  • Add load event to window
window.addEventListener('load',function(){
    
    }
  • Note: Not only can you monitor when the entire page resource is loaded, you can also bind a load event to a certain resource.

When the initial HTML document is fully loaded and parsed, the DOMContentLoaded event is triggered without waiting for style sheets, images, etc. to be fully loaded.

Event name:DOMcontentLoaded

Listening page DOM is loaded:

  • Add DOMContentLoaded event to document
document.addEventListener('DOMcontentLoaded',function(){
    
    }

Element size and position

scroll family

scenes to be used:

We want the page to scroll a certain distance, such as 100px, to show and hide certain elements. So how do we know that the page has scrolled 100 pixels?

You can use scroll to detect the scroll distance of the page

  • Get width and height
    • Get the total width and height of the element's content (excluding scroll bars) and return the value without units.
    • scrollwidth and scrollHeight
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
      
      
            width: 150px;
            height: 150px;
            background-color: pink;
            overflow: auto;
        }
    </style>
</head>
<body>
    <div>
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
        我有很多很多的内容哦
    </div>
    <script>
        // scrollwidth和scrollHeight   内容的大小(了解)
        let div = document.querySelector('div')
        console.log(div.scrollWidth)
        console.log(div.scrollHeight)
    </script>
</body>
</html>
  • Get location
    • Get the element content and scroll it to the left or up to an invisible distance
    • scrollLeft和scrollTop
    • These two properties can be modified
div.addEventListener('scroll',function() {
            console.log(this.scrollLeft)

During development, we often detect the scrolling distance of the page. For example, if the page scrolls 100 pixels, an element can be displayed or an element can be fixed.

Case

Page scroll shows back to top button

Requirement: When the page scrolls 500 pixels, the return to top button is displayed, otherwise it is hidden. Click the button at the same time to return to the top.

Analysis:
①: Use the page scroll event
②: Detect that the page scroll is greater than or equal to 100 pixels, then display the button
③: Click the button to reset the scrollTop of the page to 0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
      
      
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .content {
      
      
            height: 3000px;
            width: 1000px;
            background-color: pink;
            margin: auto;
        }

        .backtop {
      
      
            display: none;
            width: 50px;
            left: 50%;
            margin: 0 0 0 505px;
            position: fixed;
            bottom: 60px;
            z-index: 100;
        }

        .backtop a {
      
      
            height: 50px;
            width: 50px;
            background: url(../素材/images/bg2.png) 0 -600px no-repeat;
            opacity: 0.35;
            overflow: hidden;
            display: block;
            text-indent: -999em;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="content"></div>
    <div class="backtop">
        <img src="../素材/images/close2.png" alt="">
        <a href="javascript:;"></a>
    </div>
    <script>
        var i = 500
        let backtop = document.querySelector('.backtop')
        // 页面滚动事件
        window.addEventListener('scroll', function() {
      
      
            // 检测滚动距离
            let num = document.documentElement.scrollTop
            // 进行判断和隐藏
            if (num >= i) {
      
      
                // 显示返回顶部
                backtop.style.display = 'block'
            } else {
      
      
                // 或者隐藏元素
                backtop.style.display = 'none'
            }
        })
        // 点击返回顶部
        backtop.children[1].addEventListener('click',function() {
      
      
            document.documentElement.scrollTop = 0
            
        })
        

        let img = document.querySelector('img')
        img.addEventListener('click',function() {
      
      
            backtop.style.display = 'none'
            // function addi () {
      
      
            //     i += 500
            // }
            
            // // console.log(i)
        })
    </script>
</body>
</html>

There is an improvement. The idea is to increase 500 after clicking × without returning to the top pattern. The idea is to use local variable i to change global variable i

offset family

Usage scenarios:
We calculate the scrolling distance in the previous case by ourselves. It is best to do something when the page scrolls to a certain element.
To put it simply, we use js to get the position of the element on the page so that when the page scrolls to this position, we can return to the small box display at the top...

Get width and height

  • Get the element's own width and height, including the width and height set by the element itself, and padding.border.
  • offsetHeight和offsetWidth

Get location

  • Get the left and top distance of the element from the parent element you are positioning
  • Note that offsetLeft and offsetTop are read-only properties.

Case

Case

client family

Get width and height

  • Get the width and height of the visible part of the element (excluding borders, scroll bars, etc.)
  • clientwidth和clientHeight

Get location

  • Get the left and top border widths
  • Note that clientLeft and clientTop are read-only properties.

Events will be triggered when the window size changes

  • resize
window.addEventListener('resize',function() {
    
    
            //执行代码
        })

Detect screen width

window.addEventListener('resize',function() {
    
    
            let w = document.documentElement.clientWidth
            console.log(w)
            })

window object

BOM (Browser Object Model)

BOM

  • BOM (Browser Object Model) is the browser object model

Please add image description

  • Window is a global object built into the browser. All the knowledge content of WebAPls we have learned is based on the window object.
  • The window object contains five attributes: navigator, location, document, history, and screen, which is the so-called BOM (Browser Object Model)
  • Document is the basis for implementing DOM. It is actually attached to the properties of window.

Timer - Delay function

There is a function built into JavaScript to delay the execution of code, called setTimeout.

grammar:

setTimeout(回调函数,等待的毫秒数)

setTimeout is only executed once, so it can be understood as delaying the execution of a piece of code, usually omitting the window

let timer = setTimeout(回调函数,等待的毫秒数)
clearTimeout(timer)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>解除</button>
    <script>
        // 只能使用一次
        let timer = setTimeout(function(){
      
      
            console.log(111)
        },3000)
        let btn = document.querySelector('button')
        btn.addEventListener('click',function(){
      
      
            clearTimeout(timer)
        })
    </script>
</body>
</html>

recursive function

Calling yourself is a recursive function

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 所以要加一个退出条件,使得递归不死
        let num = 0
        // 死递归
        function fn() {
      
      
            num++
            console.log(111)
            if (num>= 100){
      
      
                return
            }
            fn()
        }
        fn()
    </script>
</body>
</html>

Case: Implementing setInterval using recursion

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div></div>
    <script>
        let div = document.querySelector('div')
        function fn() {
      
      
            div.innerHTML = new Date().toLocaleDateString()
            setTimeout(fn,1000)
        }
        fn()
    </script>
</body>
</html>

Comparison of two timers

  • The characteristic of setInterval is that it is executed repeatedly, and the first execution will be delayed.
  • setTimeout is characterized by delayed hot execution and is only executed once
  • setTimeout combined with recursive functions can simulate repeated execution of setlnterval
  • clearTimeout clears the scheduled tasks created by setTimeout

JS execution mechanism

Classic interview questions

console.log(111)
setTimeout(function() {
    
    
    console.log(222)
},1000)
console.log(333)

//结果111 333 222

console.log(111)
setTimeout(function() {
    
    
    console.log(222)
},0)
console.log(333)
//结果还是111 333 222

JS is single threaded

A major feature of the JavaScript language is that it is single-threaded, which means that it can only do one thing at a time. This is due to the mission of the scripting language Javascript - JavaScript was born to handle user interaction on the page and operate the DOM. For example, if we add and delete a certain DOM element, we cannot do it at the same time. It should be added first and then deleted.

Single thread means that all tasks need to be queued, and the next task will not be executed until the previous task is completed. The problem caused by this is: if the execution time of JS is too long, it will cause the rendering of the page to be inconsistent, resulting in the feeling that the page rendering and loading are blocked.

Synchronous and asynchronous

In order to solve this problem and take advantage of the computing power of multi-core CPUs, HTML5 proposes the web worker standard, which allows JavaScript scripts to create multiple threads. As a result, synchronization and asynchronous appeared in JS.

Synchronize

When the next task is executed after the previous task is completed, the execution order of the program is consistent and synchronized with the arrangement order of the tasks. For example, the synchronous method of cooking: we need to boil water to cook rice, wait for the water to boil (after 10 minutes), and then cut and stir-fry vegetables.
asynchronous

When you are doing something, because it will take a long time, you can also deal with other things while doing it. For example, in the asynchronous method of cooking, we use these 10 minutes to chop and stir-fry vegetables while boiling water.

Their essential difference: the execution order of each process on this assembly line is different.

Sync tasks

Synchronous tasks are executed on the main thread, forming an execution stack.

Asynchronous tasks

JS asynchronous is implemented through callback functions.

Generally speaking, there are three types of asynchronous tasks:

  1. Common events, such as click, resize, etc.

  2. Resource loading, such as load, error, etc.

  3. Timers, including setlnterval, setTimeout, etc.

JS execution mechanism

Asynchronous tasks are added to the task queue (the task queue is also called the message queue).

  1. First execute the synchronization tasks in the execution stack.

  2. Asynchronous tasks are placed into the task queue.

  3. Once all synchronous tasks in the execution stack are executed, the system will read the asynchronous tasks in the task queue in order, so the read asynchronous tasks end the waiting state, enter the execution stack, and start execution.

Please add image description

Because the main thread repeatedly obtains tasks, executes tasks, obtains tasks, and executes again, this mechanism is called an event loop.

location object

location object

The data type of location is an object, which splits and saves the various components of the URL address.

Common properties and methods:

  • The href attribute obtains the complete URL address and is used to jump to the address when assigning a value to it.

    // 可以得到当前文件url地址
    console.log(location.href)
    // 可以通过js方式跳转到目标地址
    location.href = 'http://www.baidu.com'
    

    Case

    Page that jumps after 5 seconds.
    Requirements: The user can click to jump. If not, it will jump automatically after 5 seconds. It requires a countdown analysis of seconds:
    ①: The target element is a link
    ②: Use a timer to set a digital countdown

    ③: When the time is up, it will automatically jump to a new page.
    After successful payment, it will jump back to the original page 1 second later.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            span{
            
            
                color: red;
            }
        </style>
    </head>
    <body>
        <a href="http://www.baidu.com">支付成功,<span>5</span>秒之后跳转首页</a>
        <script>
            let a = document.querySelector('a')
            let num = 5
            let timer = setInterval(function() {
            
            
                num--
                a.innerHTML = `支付成功,<span>${ 
              num}</span>秒之后跳转首页`
                if(num === 0) {
            
            
                    clearTimeout(timer)
                    location.href = 'https://www.bilibili.com/'
                }
            },1000)
        </script>
    </body>
    </html>
    
  • The search attribute obtains the parameters carried in the address, the part after the symbol?

    console.log(loaction.search)
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <form action="target.html">
            <input type="text" name="username">
            <button>提交</button>
        </form>
    </body>
    </html>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <script>
            console.log(location.search)
        </script>
    </body>
    </html>
    
  • The hash attribute obtains the hash value in the address, the part after the symbol #

    console.log(location.hash)
    

    The foundation for later vue routing is often used to display different pages without refreshing the page, such as NetEase Cloud Music

  • The reload method is used to refresh the current page. When the parameter true is passed in, it means a forced refresh.

    <button>点击刷新</button>
    <script>
        let btn = document.querySelector('button')
    	btn.addEventListener('click', function() {
            
            
            //刷新方法 有本地缓存 强制刷新ctrl + f5  直接更新最新内容从网上拉去,不走本地缓存
               location.reload(true)
            //强制刷新  CTRL+f5
            })
    </script>
    

navigator object

Detect browser version and platform through userAgent

history object

The data type of history is an object, which corresponds to the operations of the browser address bar, such as forward, backward, history, etc.

Common properties and methods

history object methods effect
back() Can go back function
forward() Forward function
go(parameter) If the forward and backward function parameter is 1, the foreground is 1 page, and if it is -1, the forward and backward function parameters are one page.

The history object is generally less used in actual development, but can be seen in some OA office systems.

swiper plugin

Plug-in: It is some code written by others. We only need to copy the corresponding code to implement it directly.

The basic process of corresponding effect learning plug-in

Familiarize yourself with the official website and understand what requirements this plug-in can fulfill https:// www.swiper.com.cn/

Watch online demos and find the demo that meets your needs https: //www.swiper.com.cn/demo/index.html

View the basic usage process https: // www.swiper.com.cn/usage/index.html

View the API documentation to configure your own plug-in https:// www.swiper.com.cn/api/index.html

Note: When multiple swipers are used at the same time, the class names need to be distinguished.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/swiper-bundle.min.css">
    <style>
        .box {
      
      
            width: 600px;
            height: 350px;
            background-color: pink;
            margin: 100px auto;
        }

        html,
        body {
      
      
            position: relative;
            height: 100%;
        }

        body {
      
      
            background: #eee;
            font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
            font-size: 14px;
            color: #000;
            margin: 0;
            padding: 0;
        }

        .swiper-container {
      
      
            width: 100%;
            height: 100%;
            margin-left: auto;
            margin-right: auto;
        }

        .swiper-slide {
      
      
            text-align: center;
            font-size: 18px;
            background: #fff;

            /* Center slide text vertically */
            display: -webkit-box;
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            -webkit-box-pack: center;
            -ms-flex-pack: center;
            -webkit-justify-content: center;
            justify-content: center;
            -webkit-box-align: center;
            -ms-flex-align: center;
            -webkit-align-items: center;
            align-items: center;
        }

        .swiper-slide img {
      
      
            width: 100%;
            height: 350px;
        }

        .swiper-pagination-bullet {
      
      
            width: 12px;
            height: 12px;
        }

        .swiper-pagination-bullet-active {
      
      
            background-color: #fff;
        }
    </style>
</head>

<body>
    <div class="box">
        <!-- Swiper -->
        <div class="swiper-container one">
            <div class="swiper-wrapper">
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_01.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_02.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_03.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_04.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_05.jpg" alt="">
                    </a>
                </div>


            </div>
            <!-- Add Pagination -->
            <div class="swiper-pagination"></div>
            <!-- Add Arrows -->
            <div class="swiper-button-next"></div>
            <div class="swiper-button-prev"></div>
        </div>

    </div>


    <div class="box">
        <!-- Swiper -->
        <div class="swiper-container two">
            <div class="swiper-wrapper">
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_01.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_02.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_03.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_04.jpg" alt="">
                    </a>
                </div>
                <div class="swiper-slide">
                    <a href="#">
                        <img src="./images/b_05.jpg" alt="">
                    </a>
                </div>


            </div>
            <!-- Add Pagination -->
            <div class="swiper-pagination"></div>
            <!-- Add Arrows -->
            <div class="swiper-button-next"></div>
            <div class="swiper-button-prev"></div>
        </div>

    </div>
    <script src="./js/swiper-bundle.min.js"></script>
    <!-- 要放到插件的下面 -->
    <!-- Initialize Swiper -->
    <script>
        var swiper = new Swiper('.one', {
      
      
            slidesPerView: 1,
            autoplay: {
      
      
                delay: 3000,
                stopOnLastSlide: false,
                disableOnInteraction: true,
            },
            spaceBetween: 0,
            loop: true,
            pagination: {
      
      
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
      
      
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            keyboard: true,
        });
        var swiper = new Swiper('.two', {
      
      
            slidesPerView: 1,
            autoplay: {
      
      
                delay: 5000,
                stopOnLastSlide: false,
                disableOnInteraction: true,
            },
            spaceBetween: 0,
            loop: true,
            pagination: {
      
      
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
      
      
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            keyboard: true,
        });
    </script>
</body>

</html>

local storage

With the rapid development of the Internet, web-based applications are becoming more and more common and becoming more and more complex. In order to meet various needs, large amounts of data are often stored locally. The HTML5 specification proposes relevant solutions. plan.
1. The data is stored in the user's browser.
2. It is easy to set up and read, and data will not be lost even when the page is refreshed.
3. The capacity is large, sessionStorage and localStorage are about 5M.

localStorage

1. The life cycle takes effect permanently. Unless you delete it manually, the closed page will still exist.

2. Multiple windows (pages) can be shared (the same browser can be shared)

3.Store and use in the form of key-value pairs

  • Storing data
    • localStorage.setItem(key,value)
  • retrieve data
    • localStorage.getItem(key)
  • delete data
    • localStorage.removeItem(key)

Store complex data types

  • Only strings can be stored locally, and complex data types cannot be stored. Complex data types need to be converted into JSON strings before storing them locally.

JSON.stringify (complex data type)

  • Convert complex data into JSON strings and store them in local storage

JSON.parse(JSON string)

  • Used when converting JSON strings into objects and taking them out
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 存储数据   localStorage.setItem(键,值)
        // localStorage.setItem('uname','孙悟空')
        // localStorage.setItem('age',18)
        // 获取数据    localStorage.getItem(key)
        // localStorage.getItem('uname')
        // 删除数据
        // localStorage.removeItem('uname')

        // 调用复杂类型
        let obj = {
      
      
            uname : '老八' ,
            age : 18 ,
            address : '试吃员'

        }
        // 复杂数据类型一定要转换为json字符串在进行存储
        localStorage.setItem('obj' ,JSON.stringify(obj))

        // 取数据可以使用JSON.parseo将json字符串转换为对系
        JSON.parse(localStorage.getItem('obj'))

        // // json字符串  属性和值都是双引号进行包含
        // let ob = {
      
      
        //     "uname" : "老八" ,
        //     "age" : "18 ",
        //     "address" : "试吃员"

        // }
        let object = {
      
      
            age : 18
        }
        //本地存储只能存储字符串所以我要转换转换为JSON格式的字符串
        localStorage.setItem('key',JSON.stringify(object))
        // //获取的过来的值是字符串,不是对象了没有办法直接使用,因此我们首先吧字符串转换为对象
        // JSON.parse()
        console.log(JSON.parse(localStorage.getItem('key')));


    </script>
</body>
</html>

regular expression

  • Regular expression (Regular Expression) is a pattern used to match character combinations in strings. In JavaScript, regular expressions are also objects
  • It is usually used to find and replace text that matches regular expressions. Many languages ​​support regular expressions.

Regular expression function:

  1. Form validation (match)
  2. Filter sensitive words (replace)
  3. Extract the part we want from the string (extraction)

Syntax steps:

  1. Define rules

    • grammar:

      let 变量名 = /表达式/
      
    • where // is a regular expression literal

    • For example

      let reg = /前端/
      
  2. Determine whether there is a string that matches the rules:
    The test() method is used to check whether the regular expression matches the specified string.

    • Grammar (emphasis)

      regObj.test(被检测的字符串)
      
    • Returns true if the regular expression matches the specified string, otherwise false

  3. Retrieve (find) strings that match the rules:
    The exec() method performs a search match in a specified string

    • grammar

      regObj.exec(被检测的字符串)
      

      If the match is successful, the exec() method returns an array, otherwise it returns null

Metacharacters

● Ordinary characters:

Most characters can only describe themselves. These characters are called ordinary characters, such as all letters and numbers. That is to say, ordinary characters can only match the same characters as them in the string.

● Metacharacters (special characters)
are characters with special meanings, which can greatly improve flexibility and powerful matching functions.

  • For example, it is stipulated that users can only enter 26 English letters in English. For ordinary characters, abcdefghijklm...
  • But change it to metacharacter writing: [az]

Reference documents:

  • MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
  • Regular testing tool http:// tool.oschina.net/regex

boundary character

The boundary characters (position characters) in regular expressions are used to indicate the location of characters. There are mainly two characters.

boundary character illustrate
^ Indicates matching the text at the beginning of the line (starting with sleep)
$ Indicates text matching the end of the line (who ends with it)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        console.log(//.test('哈哈哈'))
        //^开头
        console.log(/^哈/.test('二哈哈'))
        console.log(/^哈$/.test('二哈哈'))
        console.log(/^哈$/.test('哈'))
    </script>
</body>
</html>

quantifier

Quantifiers are used to set the number of occurrences of a certain pattern

quantifier illustrate
* Repeat zero or more times
+ Repeat one or more times
? Repeat zero or one time
{n} Repeat n times
{n,} Repeat n or more times
{n,m} Repeat n to m times

Note: There must be no spaces on either side of the comma.

Character class

(1) [] matches string collection

Use a hyphen – to indicate a range

// 只要中括号里面的任意字符出现都返回为true
console.log(/[abc]/.test('andy'))  //true
console.log(/[abc]/.test('bady'))  //true
console.log(/[abc]/.test('cry'))  //true
console.log(/[abc]/.test('die'))  //false

for example:

  • [az] means any 26 English letters from a to z are acceptable
  • [a-zA-Z] means both upper and lower case can be used
  • [0-9] means any number from 0 to 9 is acceptable

(2) Add the ^ negation symbol inside []

for example:

  • [^az] matches characters except lowercase letters
  • Pay attention to write it inside the square brackets

(3) Predefinition: refers to the abbreviation of some common patterns.

Reservation category illustrate
\d Matches any number between 0-9, equivalent to [0-9]
\D Matches all characters other than 0-9, equivalent to [^0-9]
\w Matches any letters, numbers and underscores, equivalent to [A-Za-z0-9_]
\W All characters except letters, numbers, and underscores, equivalent to [^A-Za-z0-9_]
\s Matches spaces (including newlines, tabs, spaces, etc.), equivalent to [\t\r\n\v\f]
\S Matches non-space characters, equivalent to [^\t\r\n\v\f]

Date format: ^\d{4} - \d{1,2} - \d{1,2}

\d{4}0-9 appears 4 times, which is the year, followed by one or two occurrences, which is 09-11 or 9-11

Guess you like

Origin blog.csdn.net/qq_66970557/article/details/125579883