Events based on JS (for personal use)

1. The event triggered when the mouse moves in the element:document.onmousemove

window.onload = function() {
   // 获取当前的鼠标的位置
    document.onmousemove = function(event) {
        // 解决兼容问题:
        event = event || window.event
        console.log('鼠标距离页面左边的位置:', event.clientX)
    }
}

2. When a mouse event occurs, get the horizontal coordinates of the mouse relative to the visible window:clientX

3. When a mouse event occurs, get the vertical coordinates of the mouse on the visible window:clientY

4. When a mouse event occurs, get the horizontal coordinates of the mouse relative to the page:pageX

5. When the mouse event occurs, get the vertical coordinates of the mouse relative to the page:pageY

6. Get the scrolling distance of the scroll bar:

  • chromeIt is considered that the scroll bar of the browser is the body, which can be document.body.scrollTopobtained by

  • fireFox\IEIt is considered that the scroll bar of the browser is html, which can be document.documentElement.scrollTopobtained by

<!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 {
            margin: 0;
            padding: 0;
        }
        .box1-parent {
            position: relative;
            width: 500px;
            height: 500px;
            border: 1px solid red;
        }
        #box1 {
            /* 添加一个绝对定位 */
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: pink;
            padding: 10px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <div class="box1-parent">
        <div id="box1"></div>
    </div>
    <script>
        // 需求:当前的box1跟随鼠标进行移动
        window.onload = function() {
            let box1Dom = document.getElementById("box1")
            document.onmousemove = function(event) {
                event = event || window.event
                // 当可见区域小于box1-parent展示的区域时,会产生滚动条,这时需要对滚动的距离做处理
                /**
                 * 获取滚动条滚动的距离:
                 *   chrome认为浏览器的滚动条是body的,可以通过document.body.scrollTop来获取
                 *   fireFox\IE认为浏览器的滚动条是html的,可以通过document.documentElement.scrollTop来获取
                */
                let st = document.body.scrollTop || document.documentElement.scrollTop
                let sl = document.body.scrollLeft || document.documentElement.scrollLeft
                box1Dom.style.left = event.clientX + sl + 'px'
                box1Dom.style.top = event.clientY + st +  'px'
            }
        }
    </script>
</body>
</html>

7. Event bubbling (bubble):

  • Definition: Upward conduction of events, when an event of a descendant element is triggered, the same event of its ancestor element will also be triggered.

  • Prevent event bubbling:event.cancelBubble = true

8. Event delegation:

  • Definition: Bind the event to the common parent element uniformly. When the event of the descendant element is triggered, it will bubble up to the ancestor element, so as to process the event through the corresponding function of the ancestor element.

  • Description: The principle of event bubbling is used to reduce the number of event bindings and improve the performance of the program

  • Detail processing: If you only need to trigger events for the current text, not for the entire block, you need to use the event.targetcurrent click object to judge.

9. Event binding:

  • 对象.事件名称 = 函数Use the form to bind the response function, it can only bind one function to one event of one element at the same time. If multiple functions are bound, the later functions will overwrite the previous ones.

  • Use addEventListener()to bind multiple response functions to an element at the same time, execution order: bind first, execute first.

    • parameter:

      • [The name of the event, without on, the type is a string]
      • [Callback function, called when an event is triggered]
      • [Whether to trigger in the capture phase, the type is a Boolean value, generally pass false]
    • IE8 and below do not support

    • 函数中的this指向当前调用的对象


  • attachEvent()Multiple response functions can be bound to an element at the same time by using , execution order: bind first and then execute.

    • parameter:

      • [The name of the event, add on, the type is a string]
      • [Callback function, called when an event is triggered]
    • IE8 and below support

    • 函数中的this指向window

10. Event dissemination:

  • Regarding the spread of events, Netscape and Microsoft have different views.

    • Microsoft Corporation: Events should be propagated from the inside out. When an event is triggered, the event of the current element should be triggered first, and then spread to the ancestor elements of the current element, that is, the event should be executed in the bubbling phase.

    • Netscape: Events should flow from the outside in. When an event is triggered, the event should be triggered on the outermost ancestor element of the current element first, and then propagated inward to descendant elements.

  • W3C combines the solutions of the two companies and divides event propagation into three stages:

    • 捕获阶段: Capture events from the outermost ancestor element to the target element, but the event will not be triggered by default at this time.

    • 目标阶段: The event captures the target element and starts firing events on the target element.

    • 冒泡阶段: The event is passed from the target element to its ancestor elements, and the events on the ancestor elements are triggered in turn.

  • If you want to trigger events during the capture phase, you need将addEventListener()的第三个参数设置为true

  • IE8 and below browsers do not have a capture phase.

<!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 id="box">按钮点击进行时间绑定的检测</button>
    <script>
        window.onload = function() {
            var boxDom = document.getElementById("box");
            // boxDom.onclick = function() {
            //     alert('使用 对象.事件的方式进行函数绑定')
            // }
            
            // IE8以上使用 addEventListener 来进行函数绑定
            // boxDom.addEventListener('click', function() {
            //     // this是boxDom
            //     alert(this)
            // });

            // IE8以下 使用 attachEvent 来进行函数绑定
            // boxDom.attachEvent('onclick', function() {
            //     // this是window
            //     alert(this);
            // });
            
            // 更改this的指向
            boxDom.attachEvent('onclick', function() {
                // this是boxDom
                alert(this);
            }.call(boxDom))
        };
    </script>
</body>
</html>

11. Event dragging:

<!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 {
            margin: 0;
            padding: 0;
        }
        #box1 {
            position: relative;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        #box2 {
            position: absolute;
            top: 200px;
            left: 200px;
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div>这是一段文字</div>
    <div id="box1"></div>
    <div id="box2"></div>
    <script>
        // 需求:拖拽box1
        window.onload = function() {
            // 获取box1对象
            var box1Dom = document.getElementById("box1")
            // 1、监听box1 鼠标按下 事件
            box1Dom.onmousedown = function(e) {
                // 4、优化鼠标的位置:鼠标对于元素的相对位置不变
                e = e || window.event
                var ol = e.clientX - box1Dom.offsetLeft // 获取鼠标相对于元素的位置
                var ot = e.clientY - box1Dom.offsetTop

                // 5、Ie8及以下阻止默认事件,chrome会报错,只有ie支持
                // 当box1Dom调用setCapture方法之后,会将下一次所有的鼠标的相关事件捕获到自身(即相当于操作box1Dom),只生效一次。
                box1Dom.setCapture && box1Dom.setCapture()

                // 2、监听 鼠标的移动事件,并且将box1的位置进行更改
                // 一定要监听全局的鼠标移动事件,如果绑定给box1,那么会出现只能向下走,不能向上走的情况
                document.onmousemove = function(event) {
                    event = event || window.event
                    box1Dom.style.left = event.clientX - ol + 'px'
                    box1Dom.style.top = event.clientY - ot +  'px'
                }


                // 3、鼠标松开,将元素固定在当前位置
                // 一定要监听全局的鼠标移动事件,如果绑定给box1,那么当页面中有其他模块的时候,当鼠标移动到其他模块之上然后松手,当前的box1还会移动。
                document.onmouseup = function() {
                    // 取消鼠标移动事件
                    document.onmousemove = null
                    // 取消鼠标松开事件
                    document.onmouseup = null
                    // 取消ie的默认事件
                    box1Dom.releaseCapture && box1Dom.releaseCapture()
                }


                /**
                 * 5、优化拖拽:
                 *   - 当我们拖拽一个网页的时候,浏览器会默认去搜索当前内容,此时会导致拖拽功能异常,这个是浏览器的默认行为。
                 *   - 除Ie8及以下的浏览器取消默认行为:return false
                */
               return false
            }
        }
    </script>
</body>
</html>

12. Wheel scrolling 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>滚轮事件</title>
    <style>
        #box1 {
            width: 100px;
            height: 100px;
            background: pink;
        }
    </style>
</head>
<body style="height: 800px;">
    <div id="box1"></div>
    <script>
        // 需求:当滚轮向上滚动,box1高度减少;当滚动向下滚动,box1高度增加
        window.onload = function() {
            var box1Dom = document.getElementById("box1")
            // 监听鼠标的滚轮事件,不兼容火狐
            box1Dom.onmousewheel = function(event) {
                event = event || window.event
                // 判断鼠标滚轮滚动的方向(火狐不支持):event.wheelDelta。向上是正值,向下负值
                // 判断鼠标滚轮滚动的方向(火狐支持):event.detail。向上是负值,向下正值
                if (event.wheelDelta > 0 || event.detail < 0) { // 向上滚动
                    box1Dom.style.height = (box1Dom.clientHeight - 10) + 'px'
                } else {
                    box1Dom.style.height = (box1Dom.clientHeight + 10) + 'px'
                }

                // 如果浏览器中有滚动条,那么鼠标滚轮会控制浏览器中的滚动条滚动,需要取消这种默认行为
                return false
            }
            // 火狐浏览器中使用addEventListener()来绑定 DOMMouseScroll事件
            // 使用addEventListener()来绑定的相应函数,取消默认行为需要用到event对象
            // event.preventDefault()
            

            // 2022年自测,兼容火狐,不兼容IE
            // box1Dom.onwheel = function() {
            //     console.log('滚动了')
            // }
        }
    </script>
</body>
</html>

13. Keyboard events:

Keyboard events are generally bound to 可以获取焦点的对象或者document.

<!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>键盘事件</title>
</head>
<body>
    <input type="text" />
    <script>
        window.onload = function() {
            /**
             * 键盘按下的时候触发,如果一直不松手,会连续触发
             *  - 事件连续触发的时候,第一次和第二次之间有间隔时间,是为了防止误操作的
             * */ 
            document.onkeydown = function(event) {
                event = event || window.event;
                /**
                 *  event.keyCode可以获取当前按键的编码
                 *  除了keyCode之外,事件对象还提供了下面的三个属性,用来判断alt、shift、ctrl是否被按下
                 *   - altKey
                 *   - ctrlKey
                 *   - shiftKey
                 *  按下返回true,未按下返回false
                 * */ 

                 // 判断当前的按键是否是y+ctrl同时按下
                 if(event.keyCode === 89 && event.ctrlKey) {
                    console.log('同时按下 y+ctrl')
                 }
            }

            // 键盘松开的时候触发
            document.onkeyup = function() {

            }


            // 获取input的Dom
            var inputDom = document.getElementsByTagName("input")[0]
            inputDom.onkeydown = function(event) {
                event = event || window.event;

                //不允许在输入框中输入数字(数字0-9的keyCode是48-57)
                console.log('event',event.keyCode)
                if(event.keyCode > 47 && event.keyCode < 58) {
                    // 键盘按下事件,在输入框中写入数据是浏览器默认行为。
                    // 阻止这种默认行为
                    return false
                }
            }
        }
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/Y1914960928/article/details/128319669