Web front end --- js event

js event (event)

(The birth of js is based on event-driven programming)

(1) event

The user acts through various behaviors (buttons, mouse clicks, mouse hover...) to cause the execution of related js codes.

Three elements of an event:

  • Event source: the person who is triggered by the event, usually binds the event
  • Event object (event): This object contains all the information related to the event
  • Event handler: the code that handles the event

<1> Define events (three ways)

[1] DOM0 mode: html tag onxxxx attribute is required to configure

Disadvantages: js and html are coupled, which violates the three-layer separation principle of w3c; in this way, the event object cannot be obtained in the event processing function; the this pointer in the event function points to the winodw object

ps:

test01(this) // When binding an event, you can pass this to the event function, and the event function needs to pass this this pointer;

console.log(this) // and this in the function directly points to the window object

<!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">
    <script>
        function test01(node){
            alert("这里是美女,只不过你看不见")
        }
        // console.log(this);
        console.log(node);
        // node:事件源
    </script>
    <title>js事件</title>
</head>
<body>
    <button onclick="test01(this);">点击一下,你就知道</button>
    <!-- 双引号中,引入javascript代码 -->
</body>
</html>

[2] DOM2 mode

It mainly involves two methods for handling the operation of specifying and removing event handlers: addEventListener() and removeEventListener() .

  • Binding events dynamically through DOM objects
<!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>DOM2</title>
</head>
<body>
    <button id="box">美女不在这</button>
    
    <a href="#" class="msg">可以在这找找看</a>
    <a href="#" class="msg">可以在这找找看</a>

    <a href="#" class="sss">你喜欢美女吗</a>
    <a href="#" class="sss">你喜欢美女吗</a>
    <a href="#" class="sss">你喜欢美女吗</a>
    <a href="#" class="sss">你喜欢美女吗</a>
    <script>

        // DOM对象()
        let box = document.getElementById("box");

        // 通过DOM对象,动态绑定事件
        box.onclick = function (ev){
            // PS:动态绑定事件的方式,第一个参数就是事件对象
            alert("那美女在哪?")
            console.log(ev); // 事件对象
            console.log(ev.target); // 事件源
            console.log(this); // 事件源,这种事件中,this指向事件源
            console.log(`x轴坐标${ev.pageX},y轴坐标${ev.pageY}`)
            
        }

        // 用className单个绑定,需确定下标
        let msg = document.getElementsByClassName("msg");
        console.log(msg);
        msg[0].onclick = function(){
            alert("这里也没有美女。")
        }

        // 多个同时绑定,需采用循环
        let sss = document.getElementsByClassName("sss");
        for(let i = 0;i < sss.length;i++){
            sss[i].onclick = function(){
                alert(`md,我喜欢的不得了,这是我第${i + 1}个按钮`);
            }
        }
    </script>
</body>
</html>

  • There is also a way to listen to events, binding events
<!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>

    <a href="http://www.baidu.com" id="go">百度</a>
    <button id="box">这里有个祢豆子</button>
    <script>
        let box = document.getElementById("box");
        // addEventListener:事件监听
        box.addEventListener("click",function(e){
            alert("点我干嘛");
            console.log(this);
            console.log(e.target);

            // 这个方法会取消冒泡 IE浏览器
            // e.cancelBubble();

            // 停止标签继续向上冒泡(阻止冒泡)  w3c
            // ev.stopPropagation();

        },true); // true:第三个参数true决定是否开启捕获流

        document.querySelector("#go").onclick = function(ev){

            alert("还是会去百度");
            // 阻止标签的默认行为
            ev.preventDefault();

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

[3] HTML event handlers

Add event handlers directly in HTML code

<input id= "btn" value= "按钮" type= "button" onclick= "showmsg();" >
  <script>
   function showmsg(){
   alert( "HTML添加事件处理" );
   }
  </script>

<2> Classification of event streams

 

Bubbling flow : Bubbling means that the event is initially received by the most specific element (the node with the deepest nesting level in the document), and then propagated up to the least specific node (document)

Capture Flow : Capture is when events are received by less specific nodes first and by the most specific nodes last.

(2) Common events

event content
onabort Image loading was interrupted
onblur element loses focus
onchange User changes field content
ondblclick mouse double click on an object
onerror An error occurred while loading the document or image
onfocus element gets focus
onkeydown A keyboard key is pressed
onkeypress A keyboard key is pressed or held down
onkeyup A keyboard key is released
onload A page or image has finished loading
onmousedown A mouse button is pressed
onmousemove the mouse is moved
onmouseout The mouse is moved from an element
onmouseover The mouse is moved over an element
onmouseup A mouse button is released
onreset reset button is clicked
onresize window or frame is resized
onselect text is selected
onsubmit The submit button is clicked
onunload user exit page

(3) Code example:

Example 1: Lottery

<!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">
    <style >
        * {
            margin: 0;
            padding: 0;
        }
        .container {
            width: 800px;
            height: 800px;
            border: 1px dashed rebeccapurple;
            position: absolute;
            left: 50%;
            margin-left: -400px;
            text-align: center;
            line-height: 100px;
        }
        .container .box, .box2 {
            width: 300px;
            height: 300px;
            background: greenyellow;
            border-radius: 50%;
            margin: auto;
            margin-top: 50px;
            text-align: center;
            line-height: 300px;
        }
        .box2 {
            background: deepskyblue;
        }
        #show {
            font-size: 30px;
            color: white;
            font-weight: bold;
        }
        #start {
            width: 300px;
            height: 50px;
            background: palegreen;
        }
    </style>
    <title>抽奖</title>
</head>
<body>
    <div class="container">
        <div class="box" id="box">
            <span id="show">
                小礼品
            </span>
        </div>
        <button id="start" onclick="start()">点击开始</button>
    </div>

    <script>
        let start = document.querySelector("#start");
        let show = document.querySelector("#show");
        let timer = null;
        let box = document.querySelector("#box");
        let isStop = false;
        let nums = ["iphone14","100w","1000w","杯子","大花棉袄","充电宝","欠我五元","谢谢惠顾"];

        start.onclick = function(){
            if(!isStop){
                isStop = true;
                timer = setInterval(function(){
                let index = Math.floor(Math.random()*nums.length);
                show.innerHTML = nums[index];
                box.className = "box2";
                start.textContent = "停止抽奖";
            },100);
            } else{
                isStop = false;
                window.clearInterval(timer);
                box.className = "box";
                start.textContent = "开始抽奖";

            }

        }
    </script>

</body>
</html>

Example 2: dragging div

<!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">
    <style>
        .box{
            width: 150px;
            height: 150px;
            border: 1px dashed rosybrown;
            position: absolute; /* 进行绝对定位 */
            left: 300px;
            top: 200px;

        }
    </style>
    <title>div的拖动</title>
</head>
<body>
    <div class="box"></div>

    <script>
        let _box = document.querySelector(".box");
        _box.onmousedown = function(e){
            let x = e.pageX-_box.offsetLeft;
            let y = e.pageY-_box.offsetTop;

            document.onmousemove = function(ev){
                let x2 = ev.pageX - x;
                let y2 = ev.pageY - y;

                _box.style.left = x2 + "px";
                _box.style.top = y2 + "px";

            }
        }
        _box.onmouseup = function(){
            document.onmousemove = null;
        }
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_62443409/article/details/131027383