Event Basis and Cases

Table of contents

        1. What is an event

        2. Event binding

        3. Event type

        4. Event propagation

        5. Case 1: The mouse follows the case

        Six: Case 2, carousel map case


1. What is an event

        For the front end : a convention made through code and certain content on the page.

        For users : a code segment that will be executed when a specified behavior is triggered.

2. Event binding

        The agreed thing is event binding .

        Event binding three elements:

                1. Event source : make an agreement with whom.

                2. Event type : agree on a behavior.

                3. Event processing function : what code is executed when the user triggers the behavior.

        Event syntax :

                EventSource.onEventType = event handler function.

3. Event type

        mouse events :

                1. click : mouse click (left button)

                2. dbclick : Double-click the mouse

                3. contextmenu: right click

                4 , mouseup : mouse up

                5 , mousedown : the mouse is pressed

                6. mouseover : mouse over

                7. mouseout : the mouse moves out

                8. mouseenter : the mouse moves in

                9 , mouseleave : the mouse moves out

                10. mousemove : mouse movement

        Keyboard events :

                1. keydown : the keyboard is pressed

                2. keyup : release the key on the keyboard

                3. keypress : keyboard typing

        Browser events :

               1. load : loading is complete

                2, scroll : scroll

                3. resize : change the size of the window

        Touch events :

                1. touchstart : touch start

               2. touchmove : touch to move

                3. touchend : touch end

                4. touchcancel : touch to cancel

        Form events :

                1. focus : get the focus

                2, blur : lose focus

                3. change : value change

                4. select : select

                5. submit : Submit

                6. reset : reset

                7. input : input

        Simple little exercise:

<style>
      div {
        width: 200px;
        height: 200px;
        background-color: pink;
      }
</style>

<div></div>
<input type="text" />
// 1、获取元素
var div=document.getElementsByTagName("div")

//2、绑定点击事件
//注意,上面获取元素使用的是标签名,返回的结果是数组类型
div[0].onclick=function(e){
    // 3、点击的时候执行的代码
    console.log("别点我!")
}


//表单事件
var inp=document.querySelector("input")
inp.onfocus=function(){
    console.log("获得焦点")
}
inp.onblur=function(){
    console.log("失去焦点")
}


//获取键盘输入的按键是哪一个
document.addEventListener("keydown",function(e){
    alert(e.keyCode)
})

4. Event propagation

        What is event propagation? Simply put, it is the browser's mechanism for responding to events (bubbling mechanism) . The browser window is the first to know what happened, and the event response mechanism is divided into three stages :

        Start event propagation ------------------

        1. Capture phase : transfer from window to target in the order of structural sub-levels;

        2. Target stage : the behavior received by the element that accurately triggers the event;

       3. The bubbling stage : pass from the target to the window in the order of the parent of the structure

        End of event propagation ---------------

        Event object : refers to an object data type that describes the event information when an event is triggered, that is, a parameter.

       Event source : That is, the element that triggers the event exactly at the target stage .

        Next, I will briefly explain it with a picture (the drawing is ugly, please forgive me):

        Suppose we click on the inner part:439754c6aa3d4dc29eb5bc7183c103eb.png

<style>
      .outer {
        width: 100px;
        height: 100px;
        background-color: pink;
        margin: 0 auto;
      }
      .center {
        width: 80px;
        height: 80px;
        background-color: green;
      }
      .inner {
        width: 50px;
        height: 50px;
        background-color: orange;
      }
      ul {
        width: 300px;
        height: 300px;
        background-color: skyblue;
        margin: 0 auto;
        list-style: none;
        display: flex;
      }
      ul > li {
        flex-direction: column;
        height: 50px;
        background-color: pink;
        margin-right: 20px;
        margin-top: 20px;
        cursor: pointer;
      }
</style>
<div class="outer">
      <div class="center">
        <div class="inner"></div>
      </div>
</div>

<ul>
      <li style="flex: 1">1</li>
      <li style="flex: 1">2</li>
      <li style="flex: 1">3</li>
</ul>
//获取需要的元素
var outer=document.querySelector(".outer")
var center=document.querySelector(".center")
var inner=document.querySelector(".inner")

//给每个变量绑定点击事件
outer.onclick=function(){
    alert("我是outer")
}
center.onclick = function () {
    alert("我是center");
};
inner.onclick = function (e) {
    alert("我是inner");
};

        When you just write like this, you try to click on the innermost layer, which is the inner layer, and you will find that not only the inner bullet box appears, but also the center and outer bullet boxes appear after you click the button. This is the event bubbling mechanism .

        We definitely don't want such a situation to happen, so how to prevent the occurrence of bubbling events? Very simple, add a code: e.stopPropagation()

inner.onclick = function (e) {
    alert("我是inner");
    // 阻止事件传播
    e.stopPropagation();
};

        The parameter e here is the event object, and the stopPropagation method of the event object can prevent the occurrence of the bubbling mechanism.

        Let’s briefly talk about event delegation here , the principle is to use the bubbling mechanism to achieve:

      //   事件委托
      //   获取ul元素
      var ul = document.querySelector("ul");
      ul.onclick = function (e) {
        // 获取事件源,即点击的是哪一个元素
        // console.log(e.target);

        if (e.target.tagName === "LI") {
          console.log("你点击的是li");
        }
      };

        The above code is to bind the event that should be bound to the li tag to the ul tag, which is the event delegation (can be compared with jQuery's event delegation).

        After understanding the above basic knowledge, let's do two simple small cases.

5. Case 1: The mouse follows the case

        Basic requirements: No matter where the mouse moves, there will be a small icon to follow the mouse.

        Material requirements: a picture.

        Knowledge Supplement:

                1. offsetX and offsetY: The coordinates of the mouse relative to the event source .

                2. clientX and clientY: the coordinates of the mouse relative to the visible window of the browser .

                3. pageX and pageY: the coordinates of the mouse relative to the document flow of the page .

                The coordinates of the cursor relative to the window: event object.clientX and event object.clientY

        Next is the code implementation. Before viewing the following code, please try to do it yourself to see if it can be realized.

<style>
      img {
        width: 50px;
        height: 50px;
        /* 下面三行代码是关键,根据偏移值来实现 */
        position: absolute;
        top: 0;
        left: 0;
      }
</style>

<img src="这里填自己的图片路径"  />
<script>

    var imgBox=documentSelector("img")
    
    //给鼠标移动事件绑定一个方法
    
    document.onmousemove=function(e){
        //拿到光标相对于窗口的坐标
        var x=e.clientX
        var y=e.clientY

        //将拿到的坐标赋值给top和left
        imgBox.style.top=y+"px"
        imgBox.style.left=x+"px"
    }

</script>

Six: Case 2, carousel map case

        Requirements: Use JS to realize the carousel image effect, click the left and right buttons to switch, and click the focus (the small dot below the picture) to switch.

        Effect:f9f6dbf04c0d4377a2883810ae661f72.png

         First the HTML structure:

<!-- 图片区域 -->
<div class="banner">
    <!-- 图片显示 -->
    <ul class="imgBox">
        <li class="active"><img src="图片地址" /></li>
        <li><img src="图片地址" /></li>
        <li><img src="图片地址" /></li>
    </ul>
    
    <!-- 焦点区域 -->
    <ol>
        <li class="active"></li>
        <li class="active"></li>
        <li class="active"></li>
    </ol>

    <!-- 左右切换按钮 -->
    <div class="left">&lt;</div>
    <div class="right">&gt;</div>
</div>

        Next is the CSS:

<style>
    *{
        margin:0;
        padding:0;
    }
    html,body{
        height:100%;
    }
    /*去除默认样式*/
    ul,ol{
        list-style:none;
    }
    img{
        width:100%;
        height:500px;
        display:block;
    }
    .banner{
        width:100%;
        height:100%;
        position:relative;
    }
    /* 给图片设置样式 */
    .banner>ul>li{
        position:absolute;
        width:100%;
        height:100%;
        left:0;
        top:0;
        /*透明度为0*/
        opacity:0;
        transition:opacity 0.5s linear;
    }
    

</style>

        If the style is written here, the running effect will be that no picture is displayed, let's continue to write:

    /*
        接着上面的写
    */
    .banner > ul > li.active {
        opacity: 1;
    }
    /* 设置焦点区域样式 */
    .banner > ol {
        width: 200px;
        height: 30px;
        position: absolute;
        left: 30px;
        bottom: 30px;
        background-color: rgba(0, 0, 0, 0.5);

        display: flex;
        justify-content: space-around;
        align-items: center;
        border-radius: 15px;
      }
    .banner > ol > li {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: white;
      }
    .banner > ol > li.active {
        background-color: orange;
      }
    /* 设置左右按钮 */
    .banner > div {
        width: 40px;
        height: 60px;
        position: absolute;
        top: 50%;
        margin-top: -30px;
        background-color: rgba(0, 0, 0, 0.5);

        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 30px;
        color: white;
        cursor: pointer;
      }
    .banner > div.left {
        left: 0;
      }
    .banner > div.right {
        right: 0;
      }

        So far, the style has basically been completed, and the next thing we need is JS to realize the function:

<script>
    //需要获取所有的图片和焦点按钮
    var imgs=document.querySelectorAll("ul>li")
    var points=document.querySelectorAll("ol>li")

    // 准备一个变量表示当前是第几张
    var index=0
    
    // 这里约定参数为true时切换下一张,参数为false时切换上一张,参数为数字时就切换到第几张
    function changeOne(type){
        // 让当前这一张消失
        imgs[index].className=""
        points[index].className=""
        
        //根据参数type传递的值来切换index的值
        if(type==true)
        {
            index++;
        }else if(type==false){

            index--
        }else{
            index=type
        }


        //在改变index的值之后,需要判断index的值是否溢出,否则会切换失败
        if(index>=imgs.length)
        {
            //当index的值越界之后,重新回到第一张
            index=0;
        }
        if(index<0)
        {
            //如果index小于0,则回到最后一张
            index=imgs.length-1
        }
        
        //改变index后的显示
        imgs[index].className="active"
        points[index].className="active"
    }

    //给轮播图添加一个点击事件,这里使用事件委托,下面这句话加到最前面
    var banner=document.querySelector(".banner")
    
    banner.onclick=function(e){
        if (e.target.className === "left") {
          changeOne(false);
        }
        if (e.target.className === "right") {
          changeOne(true);
        }
        if (e.target.dataset.name === "point") {
           // 给焦点添加点击事件的时候,在焦点部分的HTML代码,给每个li标签添加自定义属性
            // 这里的dataset.name就是data-name
            // 这里的dataset.index就是data-index
          changeOne(e.target.dataset.index);
        }
    }

    //   自动切换
    setInterval(function () {
        changeOne(true);
    }, 3000);
</script>

        Add custom attributes to the code of the focus area. The purpose of adding custom attributes is to facilitate the acquisition of which element is clicked:

    <!-- 焦点区域 -->
      <ol>
        <li class="active" data-name="point" data-index="0"></li>
        <li data-name="point" data-index="1"></li>
        <li data-name="point" data-index="2"></li>
      </ol>

        The carousel map has been completed so far, everyone, hurry up and try it! If you encounter any problems, please leave a message below or private message me, I will reply when I see it~

Guess you like

Origin blog.csdn.net/txl2498459886/article/details/125115191