Event object, event delegation and event type of DOM event mechanism

1. Event object event

The event object only exists for as long as the event handler executes, and is destroyed once execution is complete.

1.1 Prevent default events from happening

preventDefault() method

Role: prevent the default action of a specific event. For example, the default for a link to navigate to the URL specified by the href attribute when clicked or modify the default event for form submission. If you want to prevent these behaviors, you can cancel it in the onclick event handler

  <a href="https://www.baidu.com">百度一下</a>
  <!-- 表单提交 -->
  <form action="test.php">
    <input type="submit" value="提交" id="inp1">
  </form>
  <script>
    // 阻止a标签的默认事件发生
    var a = document.getElementsByTagName('a')[0]
    a.onclick = function () {
      event.preventDefault();
      console.log('a被点击了');
    }
    // 阻止表单事件的默认行为
    var inp1 = document.getElementById('inp1')
    inp1.onclick = function () {
      event.preventDefault();
      console.log('表单提交了');
    }
  </script>

2. Event delegation

Event delegation is to delegate what to do to the parent element (or the parent element of the parent element) when the event is triggered. That is: use the principle of bubbling to add events to the parent, and perform corresponding operations by judging the subset of event sources. Avoid adding event listeners to each specific node, causing code delays in advance

  <ul id="father">
    <li id="li1">who</li>
    <li id="li2">where</li>
    <li id="li3">what</li>
  </ul>
  <script>
    // 分别获取三个子元素的节点
    var li1 = document.getElementById('li1')
    var li2 = document.getElementById('li2')
    var li3 = document.getElementById('li3')
    // 方法一 给三个子元素节点绑定事件
    // li1.onclick = function () {
    //   console.log('zhangsan');
    // }
    // li2.onclick = function () {
    //   console.log('北京');
    // }
    // li3.onclick = function () {
    //   console.log('爬长城');
    // }
    // 方法二 利用事件委托
    // 获取父元素节点
    var father = document.getElementById('father')
    // 给li的父元素添加了一个 onclick 事件处理程序
    father.addEventListener('click', function (event) {
      switch (event.target.id) {
        case 'li1':
          console.log('zhangsan');
          break;
        case 'li2':
          console.log('北京');
          break;
        case 'li3':
          console.log('爬长城');
          break;
        default:
          break;
      }
    })
  </script>

Since all list items are descendants of this element, their events will bubble up and will eventually be handled by this function. The target of the event is each clicked list item, which can be determined by checking the id attribute of the event object, and then perform the corresponding operation. Compared to the previous, using event delegation does not cause upfront delays, because only one DOM element is accessed and one event handler is added. The result is no difference to the user, but this way uses less memory.

Events that are best suited for event delegation include: click, mousedown, mouseup, keydown, and keypress.

3. Event type

(1) User Interface Event (UIEvent) : A common browser event involving interaction with the BOM.

load

Triggered when the page is loaded on the window; triggered when all panes <frame> are loaded on the window cover <frameset>; triggered when the image is loaded on the <img> element; triggered when the corresponding object is loaded on the <object> element after triggering.

<script>
  //在 window 上当页面加载完成后触发
  window.onload = function () {
    console.log('onload');
  }
  //在<img>元素上当图片加载完成后触发
  document.getElementsByTagName('img')[0].onload = function () {
    console.log('img onload');
  }
</script>

unload

Triggered on the window when the page is completely unloaded; on the frameset when all frames are unloaded; on the <object> when the embedded content is unloaded.

<script>
  //当页面完全卸载后在window上触发
  window.onunload = function () {
    console.log('onunload');
  }
</script>

select

Fires when the user selects one or more characters on a textbox (<input> or textarea).

<input type="text" id="inp">
<script>
  //获取input引用
  var inp = document.getElementById('inp');
  // select
  inp.onselect = function (event) {
    // 通过window.getSelection()获取到选中的部分
    console.log(window.getSelection().toString());
  }
</script>

resize

On a window or pane, fires when the window or pane is scaled.

<body onresize="myFun()">
  <script>
    function myFun() {
      console.log(window.outerHeight, window.outerWidth);
    }
  </script>
</body>

scroll

Fired on an element when the user scrolls the element containing the scrollbar. The <body> element contains the scroll bars for the loaded page.

<div id="d1" style="width: 100px;height: 100px;border: 1px solid; overflow: auto;">我是div标签我是div标签我是div标签我是div标签我是div标签我是div标签我是div标签我是div标签我是div标签我是div标签我是div标签</div>
<script>
  var d1 = document.getElementById('d1');
  d1.onscroll = function () {
    console.log('onscroll');
  }
</script>

(2) Focus Event (FocusEvent) : Triggered when the element gains and loses focus.

focus

Fired when an element gains focus. This event does not bubble and is supported by all browsers.

  <input type="text" name="" id="inp">
  <script>
    var inp = document.getElementById('inp')
    // 聚焦(获得焦点)
    inp.onfocus = function () {
      console.log('focus');
    }
    // 失焦
    inp.onblur = function (event) {
      console.log(event.target.value);
    }
  </script>

(3) Mouse event (MouseEvent) : Triggered when the mouse is used to perform certain operations on the page.

click

// Triggered when the user clicks the primary mouse button (usually the left button) or presses the Enter key on the keyboard

dblclick

// Triggered when the user double-clicks the primary mouse button (usually the left button).

mousedown

// Triggered when the user presses any mouse button, not via the keyboard.

mouseenter

// Triggered when the user moves the mouse cursor from outside the element to inside the element.

mouseleave

// Triggered when the user moves the mouse cursor from inside to outside the element.

mousemove

Fires repeatedly when the mouse cursor moves over the element, not via the keyboard.

mouseout

// Fires when the user moves the mouse cursor from one element to another. The element moved to can be an outer element of the original element, or a child element of the original element, and cannot be triggered by the keyboard.

mouseover

// Triggered when the user moves the mouse cursor from outside the element to inside the element, not via the keyboard.

mouseup

// Triggered when the user releases the mouse button, not via the keyboard.

  <div id="div1"></div>
  <script>
    var div1 = document.getElementById('div1')
    // 单击事件
    div1.onclick = function () {
      console.log('单击');
    }
    // 双击事件
    div1.ondblclick = function () {
      console.log('双击触发');
    }
    // 鼠标移入
    div1.onmouseenter = function () {
      console.log('鼠标移入');
    }
  </script>

(4) Wheel Event (WheelEvent) : Triggered when the mouse wheel (or similar device) is used.

  <div id="div1"></div>
  <script>
    var div1 = document.getElementById('div1')
    // 鼠标移出
    div1.onmouseleave = function () {
      console.log('鼠标移出');
    }
  </script>

(5) Keyboard Event (KeyboardEvent) : Triggered when the keyboard is used to perform certain operations on the page.

Keyboard events contain 3 events:

keydown: Triggered when the user presses a key on the keyboard, and keeps pressing it will trigger repeatedly

keypress: triggers when the user presses a key on the keyboard and generates characters, and keeps pressing and triggering repeatedly

keyup: Triggered when the user releases a key on the keyboard.

When the user presses a character key on the keyboard, the keydown event is first triggered, then the keypress event is triggered, and finally the keyup event is triggered. If a character key is held down, keydown and keypress fire repeatedly until the key is released.

For non-character keys, when you press this key on the keyboard, the keydown event will be triggered first, and then the keyup event will be triggered. If a non-character key is held down, the keydown event will be triggered repeatedly until the key is released, at which point the keyup event will be triggered.

(6) Input event (InputEvent) : Triggered when text is entered into the document.

There is only one input event, textInput. This event is an extension to the keypress event to more conveniently intercept text input before it is displayed to the user.

Comprehensive case of keyboard events and input events

  <input type="text" id="inp1">
  <script>
    var inp1 = document.getElementById('inp1');
    // 按下某个按键是触发
    inp1.onkeydown = function (event) {
      if (event.keyCode == 13) {
        console.log('确认');
        console.log(this.value);
      }
    }
    // 按下键盘上某个键并产生字符时触发,而且持续按住会重复触发
    inp1.onkeypress = function (event) {
      console.log(event.keyCode);
    }
    // 用户释放键盘上某个键时触发
    inp1.onkeyup = function (event) {
      console.log(event.keyCode);
    }
    // 键盘输入事件 必须使用DOM2级事件
    inp1.addEventListener('textInput', function (event) {
      console.log(event.data);
    })
  </script>

More event types can be found at:  Event - Web API interface reference | MDN

Guess you like

Origin blog.csdn.net/qq_50748038/article/details/126512151