search
HomeWeb Front-endFront-end Q&AWhat are JavaScript event types

What are JavaScript event types

Dec 08, 2021 pm 03:43 PM
javascriptevent type

In JavaScript, event type refers to the way the event is triggered. A simple understanding is what event is triggered; event types include: UI events, focus events, mouse and wheel events, keyboard and text events, and compound events. , change events, HTML5 events, device events, touch and gesture events, etc.

What are JavaScript event types

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Events refer to behaviors that can be detected by JavaScript and are a "trigger-response" mechanism. These behaviors refer to specific actions such as page loading, mouse click/double-click, mouse pointer sliding over a certain area, etc. It plays a very important role in achieving the interactive effect of the page.

Events consist of three parts: event source, event type and event handler, also known as the "three elements of events".

  • Event source: the element that triggers (is) the event

  • Event type: the way the event is triggered (such as mouse click or keyboard click)

  • Event handler: code to be executed after the event is triggered (function form)

The above three elements can be simply understood as "who triggers event", "what event was triggered", "what to do after the event is triggered".

There are many types of events that may occur in web browsers. Here I will mainly focus on the following commonly used event types:

  • UI events
  • Focus events
  • Mouse and wheel events
  • Keyboard and Text event
  • Composite event
  • Change event
  • HTML5 event
  • Device event
  • Touch and gesture event

Part One: UI Events

The UI in the UI event is (User Interface, User Interface), which is triggered when the user interacts with the elements of the page sauna.

UI events mainly include load, unload, abort, error, select, resize, scroll events.

1.load event

 This event occurs when the page is completely loaded (including all images, js files, css external resources such as files), the load event on the window will be triggered.

 This event is the most commonly used event in JavaScript. For example, we often use window.onload=function(){}; this form, that is, when the page Execute the functions after it is completely loaded.

In addition, I have never known that this event can also be used on other elements, such as image elements, as shown below:

<img  src="/static/imghwm/default1.png" data-src="smile.png" class="lazy" alt="What are JavaScript event types" >  

 That is, when the image is fully loaded There will be a pop-up window after coming out. Of course, it can also be implemented using JS, as shown below:

var img=document.getElementById("img");
EventUtil.addHandler(img,"load",function(){
      event=EventUtil.getEvent(event);
      alert(EventUtil.getTarget(event).src);
});

2.unload event

 Obviously, this event is relative to the load event of. Triggered after the document is completely unloaded. The unload time is triggered when the user switches from one page to another. The most common use of this event is to clear references to avoid memory leaks.

 This event also has two ways to specify. One is the JavaScript method, using EventUtil.addHandler(); the other is to add a feature to the body element.

It is worth noting that you must be careful when writing the code in the onload event, because it is triggered after the page is unloaded, so Those objects that exist after the page is loaded may not necessarily exist after onload is triggered!


3.resize event

  When the browser window is resized to a new width or height, the resize event is triggered. This event is triggered on the window. #So the handler can also be specified through the onresize attribute in JS or the body element.  


  If you write this code, a window will pop up when the size of the browser changes.

4.scroll event

This event will be triggered repeatedly while the document is scrolled, so the code of the event handler should be kept as simple as possible.

第二部分:焦点事件

  焦点事件会在页面元素获得或失去焦点时触发。主要有下面几种:

  • blur   在元素失去焦点时触发。这个事件不冒泡,所有浏览器都支持。
  • focus   在元素获得焦点时触发。这个事件不冒泡,所有浏览器都支持。
  • focusin  在元素获得焦点时触发。这个事件冒泡,某些浏览器不支持。
  • focusout 在元素失去焦点时触发。这个事件冒泡,某些浏览器不支持。

  注意:即使blur和focus不冒泡,也可以在捕获阶段侦听到他们。

第三部分:鼠标与滚轮事件

  鼠标事件是Web开发中最常用的一类事件,因为鼠标是最主要的定位设备。

  • click---用户单击鼠标左键或按下回车键触发
  • dbclick---用户双击鼠标左键触发。
  • mousedown---在用户按下了任意鼠标按钮时触发。
  • mouseenter---在鼠标光标从元素外部首次移动到元素范围内时触发。此事件不冒泡
  • mouseleave---元素上方的光标移动到元素范围之外时触发。不冒泡
  • mousemove---光标在元素的内部不断的移动时触发。
  • mouseover---鼠标指针位于一个元素外部,然后用户将首次移动到另一个元素边界之内时触发。
  • mouseout---用户将光标从一个元素上方移动到另一个元素时触发。   
  • mouseup---在用户释放鼠标按钮时触发。

  注意到:上述所有事件除了mouseenter和mouseleave外都冒泡。

  重要:只有在同一个元素上相继触发mousedown和mouseup事件,才会触发click事件。同样,只有在同一个元素上触发两次click事件,才会触发dbclick事件。

  dbclick事件的产生过程如下:

  • mousedown

  • mouseup

  • click

  • mousedown

  • mouseup

  • click

  • dbclick

  上面介绍了有关鼠标的事件,下面介绍一些对于鼠标光标的位置:客户区坐标位置、页面坐标位置、屏幕坐标位置

一、客户区坐标位置

  通过客户区坐标可以知道鼠标是在视口中什么位置发生的。

  clientX和clientY分别表示鼠标点击的位置。以body的左上角为原点,向右为X的正方向,向下为Y的正方向。这两个都是event的属性。举例如下:

    <button>点我</button>
    <script>
        var button=document.getElementById("clickMe");
        button.onclick=function(event){
            alert(event.clientY+""+event.clientX);
        };    
     </script>

  当我点击按钮的左上角时,显示为00。效果如下:

二.页面坐标位置

  和客户区坐标位置不同,页面坐标位置表示鼠标光标在页面而非视口中的位置。因此坐标是从页面本身而非视口的左边和顶边计算的。如果前面的话不能很好的理解,接着看这里:在页面没有滚动的情况下,页面坐标位置和客户区坐标位置是相同的。

  页面坐标

nbsp;html>


    <meta>
    <title>页面坐标位置</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        p{
            width: 800px;
            height: 1200px;            /*我的电脑的视口高度为960px;*/
            background: #ccc;
        }    </style>


    <p></p>
    <button> 点击我</button>
    <script>        
    var button=document.getElementById("button");
        button.onclick=function(){
            alert("pageX为"+event.pageX+"pageY为"+event.pageY);
        };    </script>

在上面的例子中,我把p的高设置为了1200px;而我的浏览器视口高度为960px;所以一定需要滚动我们才能点击按钮,最终得到的结果是:pageX为13pageY为1210。

然而IE8及更早的浏览器是不支持事件对象上的页面坐标的,即不能通过pageX和pageY来获得页面坐标,这时需要使用客户区坐标和滚动信息来计算了。而滚动信息需要使用document.body(混杂模式)、document.documentElement(标准模式)中的scrollLeft和scrollTop属性。举例如下:

    <button> 点击我</button>
    <script>        var button=document.getElementById("button");
        button.onclick=function(){            
        var pageX=event.clientX+(document.body.scrollLeft||document.documentElement.scrollLeft);           
         var pageY=event.clientY+(document.body.scrollRight||document.documentElement.scrollRight);
            alert("pageX为"+pageX+"pageY为"+pageY);
        };    
      </script>

此例子在IE浏览器下可得到同样结果。

三.屏幕坐标位置

  与前两者又有所不同,鼠标事件发生时,还有一个光标相对于整个电脑屏幕的位置。通过screenX和screenY属性就可以确定鼠标事件发生时鼠标指针相对于整个屏幕的位置。举例如下:

nbsp;html>


    <meta>
    <title>页面坐标位置</title>
    <style>
        *{
            margin:0;
            padding:0;
        }    </style>


    <button> 点击我</button>
    <script>        
    var button=document.getElementById("button");
        button.onclick=function(){
            alert("X为:"+event.screenX+"Y为:"+event.screenY);
        };    
      </script>

最终的结果如下:

显然screenX和screenY是相对于屏幕的左方和上方的。

四.修改键

  当点击某个元素时,如果我们同时按下了ctrl键,那么事件对象的ctrlKey属性值将为true,否则为false,对于alt、shift、meta(windows键盘的windows键、苹果机的Cmd键)的事件属性altKey、shiftKey、metaKey同样如此。下面举例如下:

    <button> 点击我</button>
    <script>        
    var button=document.getElementById("button");
        button.onclick=function(){            
        var array=new Array();            
        if(event.shiftKey){
                array.push("shift");
            }            if(event.ctrlKey){
                array.push("ctrl");
            }            if(event.altKey){
                array.push("alt");
            }            if(event.metaKey){
                array.push("meta");
            }
            alert(array.join(","));
        };    
      </script>

这个例子中,我首先创建了一个array数组,接着如果我按下了那几个键,就会存入相应的名称。这里我同时按下了四个键,结果如下:

即最终将数组中的四个值拼接成了字符串显示出来。

七、鼠标滚轮事件

    <script>
        document.onmousewheel=function(){
            alert(event.wheelDelta);
        };    
     </script>

当我向下滚动滚轮时,效果如下:

 

 

 

第四部分:键盘和文本事件

  该部分主要有下面几种事件:

  • keydown:当用户按下键盘上的任意键时触发。按住不放,会重复触发。

  • keypress:当用户按下键盘上的字符键时触发。按住不放,会重复触发。

  • keyup:当用户释放键盘上的键时触发。

  • textInput:这是唯一的文本事件,用意是将文本显示给用户之前更容易拦截文本。

  这几个事件在用户通过文本框输入文本时才最常用到。

  键盘事件:

    document.addEventListener("keydown",handleKeyDownClick,false);

        function handleKeyDownClick(event) {            
        var e = event||window.event||arguments.callee.caller.arguments[0];            
        if (e&&e.keyCode == 13) {
                alert("keydown");
            }
        }

【相关推荐:javascript学习教程

The above is the detailed content of What are JavaScript event types. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools