search
HomeWeb Front-endJS TutorialDetailed explanation of the use of JavaScript focus events, mouse events and scroll wheel events_javascript skills

Focus Event

Generally, these events are used in conjunction with the document.hasFocus() method and the document.activeElement property. Mainly include:

blur: The element loses focus and will not bubble;
DOMFocusIn: Same as HTML event focus, abandoned in DOM3, use focusin;
DOMFocusOut: Same as HTML event blur, abandoned in DOM3, use focusout;
focus: The element gets focus and does not bubble back;
focusin: Get focus, equivalent to HTML event focus, but will bubble;
focusout: lose focus, equivalent to HTML event blur;
Such as:

window.onfocus = function () {
  console.log('focus'); //focus
  console.log(document.hasFocus()); //True
}
window.onblur = function () {
  console.log('blur'); //blur
  console.log(document.hasFocus()); //False
}

When the focus moves from one element to another on the page, the following event will be triggered:

focusout --> focusin --> blur --> DOMFocusOut --> focus --> DOMFocusIn

Mouse events

9 mouse events are defined in DOM level 3 events:

click
dblclick
mousedown:用户按下任意鼠标按钮时触发,不能通过键盘触发这个事件;
mouseup:用户释放鼠标按钮时触发,不能通过键盘触发这个事件;
mousemove:不能通过键盘触发这个事件;
mouseenter:不冒泡,且光标移动到后代元素上不会触发;
mouseleave:不冒泡,且光标移动到后代元素上不会触发;
mouseover:光标移动到后代元素上会触发;
mouseout:光标移动到后代元素上会触发;

For example:

div.onmouseover = function() {
  console.log('mouseover'); //在子元素上会触发
}
div.onmouseout = function() {
  console.log('mouseout'); //在子元素上会触发
}
div.onmouseenter = function() {
  console.log('mouseenter'); //在子元素上不会触发
}
div.onmouseleave = function() {
  console.log('mouseleave'); //在子元素上不会触发
}

Only when the mousedown and mouseup events are divided successively on the same element, the click event will be triggered; only when the click event is triggered twice, the dblclick event will be triggered in sequence.

The order is as follows:

mousedown --> mouseup --> click --> mousedown --> mouseup --> click --> dblclick

There is a bug in versions before IE8. In the double-click event, the second mousedown and click events will be skipped

Wheel event

Client area coordinate position clientX and clientY attributes

For example:

window.onmousemove = function() {
    clickX = event.clientX;
    clickY = event.clientY;
    var div = document.createElement("img");
    div.src = "hhh.gif"
    div.style.position = "absolute";
    div.style.width = '100px';
    div.style.left = clickX + "px";
    div.style.top = clickY + "px";
    document.body.appendChild(div);
};

Page coordinate positions pageX and pageY;

window.onclick = function() {
    clickX = event.pageX;
    clickY = event.pageY;
    var div = document.createElement("img");
    div.src = "ppp.png"
    div.style.position = "absolute";
    div.style.width = '100px';
    div.style.left = clickX + "px";
    div.style.top = clickY + "px";
    document.body.appendChild(div);
};

This page coordinate position is not supported in IE8 and earlier versions. It can be calculated by using the scrollLeft and scrollTop attributes in document.body in mixed mode and document.documentElement in standard mode:

if (clickX === undefined) {
  clickX = event.clientX + (document.body.scrollLeft || document.documentElement.scrollLeft);
};
if (clickY === undefined) {
  clickY = event.clientY + (document.body.scrollTop || document.documentElement.scrollTop);
};

Screen coordinate positions screenX and screenY;

Through this attribute, you can get the coordinates relative to the screen.

Modification keys

Modification keys include Shift, Ctrl, Alt, and Meta (Windows key on Windows, Cmd key on Mac); the corresponding modifier key states are shiftKey, ctrlKey, altKey, and metaKey. These attributes contain Boolean values. , true if the corresponding key is pressed, false otherwise. Such as:

var array = [];
var timing = setTimeout(showArray, 100);

window.onclick = function() {
  if (event.shiftKey) {
    array.push("shift");
  };
  if (event.ctrlKey) {
    array.push("ctrl");
  };
  if (event.altKey) {
    array.push("alt");
  };
  if (event.metaKey) {
    array.push("meta");
  };
};

function showArray() {
  var str = array.toString();
  var newP = document.createElement("p");
  newP.appendChild(document.createTextNode(str));
  document.body.appendChild(newP);
  timing = setTimeout(showArray, 1000);
}

Related elements

event.relatedTarget and event.target;

The relatedTarget attribute provides information about related elements. This attribute only contains values ​​for mouseover and mouseout events; for other events, the value is null; versions before IE8 do not support the relatedTarget attribute. When the mouseover event is triggered, the related elements are saved in the fromElement attribute of IE; when the mouseout event is triggered , the relevant elements are stored in IE's toElement attribute.

For example:

var dot = document.getElementById("dot");
dot.onmouseout = function (){
  console.log("mouse out from" + event.target.tagName + "to" + event.relatedTarget.tagName);
};

For example:

function getRelatedTarget() {
  if (event.ralatedTarget) {
    return event.relatedTarget;
  } else if (event.toElement) {
    return event.toElement;
  } else if (event.fromElement) {
    return event.fromElement;
  } else {
    return null;
  }
}

Mouse Buttons

button attribute

The event.button attribute of DOM has three values: 0 for the primary mouse button, 1 for the middle mouse button, and 2 for the secondary mouse button. In normal settings, the primary mouse button is the left mouse button; the secondary mouse button is the right mouse button.

IE8 and previous versions also provide the button attribute, but the value of this attribute is very different from the DOM button attribute:

0: No mouse button pressed;
1: Main mouse button;
2: Secondary mouse button;
3: Press the primary and secondary mouse buttons simultaneously;
4: Middle mouse button;
5: Press the main mouse button and the middle mouse button at the same time;
6: Press the second mouse button and the middle mouse button at the same time;
7: Press three mouse buttons simultaneously

Compatible version:

function getButton() {
  if (document.implementation.hasFeature("MouseEvents", "2.0")) {
    return event.button;
  } else {
    switch (event.button) {
      case 0:
      case 1:
      case 3:
      case 5:
      case 7:
        return 0;
      case 2:
      case 6:
        return 2;
      case 4:
        return 1;
    }
  }
}

In addition, if you want to block the right mouse button, you should use:

document.oncontextmenu = function(event) {
  // if (window.event) {
  //   event = window.event;
  // }
  // try {
  //   var the = event.srcElement;
  //   if (!((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) {
  //     return false;
  //   }
  //   return true;
  // } catch (e) {
  //   return false;
  // }
  return false;
}

This event is defined by HTML5 and will be discussed later

More event information

detail attribute

For mouse events, detail contains a value indicating how many clicks occurred at a given position (one mousedown and one mouseup). The number starts counting from 1. If the position has moved between mousedown and mouseup , the detail will be reset to 0, and if the click interval is too long, it will also be reset to 0.

Mouse wheel event

mousewheel event and wheelDelta attribute

When the user scrolls the page vertically, the mousewheel will be triggered. The wheelDelta attribute in the event object means that when the user rolls the wheel forward, the wheelDelta is a multiple of 120; when the user rolls the wheel backward, the wheelDelta is -120. multiple. Such as:

var clientHeight = document.documentElement.clientHeight;
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
  divs[i].style.height = clientHeight + "px";
};

window.onmousewheel = function () {
  if (event.wheelDelta <= -120) {
    window.scrollBy(0,clientHeight);
  }else if(event.wheelDelta >= 120){
    window.scrollBy(0,-clientHeight);
  };
}

另外,在Opera 9.5之前的版本中,wheelDelta值的正负号是颠倒的。

此外,Firefox支持一个名为DOMMouseScroll的类似事件,也是在鼠标滚动滚轮时除法。有关鼠标滚轮的信息保存在detail属性中。向前滚动这个属性的值为-3的倍数,向后滚动,这个属性的值是3的倍数。

通用版:

function getWheelDelta() {
  if (event.wheelDelta) {
    return (client.engine.opera && client.engine.opera < 9.5 &#63; -event.wheelDelta : event.wheelDelta);
  } else {
    return -event.detail * 40;
  };
}

触摸设备

iOS和Android设备中:

不支持dblclick;
轻击可单击元素会触发mousemove;如果此操作会导致内容变化,将不再有其他事件发声;如果屏幕没有发生变化,那么依次发生mousedown、mouseup和click事件;
mousemove事件也会触发mouseover和mouseout事件;
两个手指操作会触发mousewheel和scroll;

无障碍性问题

使用click事件执行代码;

不要使用onmouseover向用户显示新的信息;
不要使用dblclick执行重要的操作;

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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment