javascript: Mouse Events

Original sentence: Https://Wangdoc.Com/javascript/index.Html

Mouse Events

The type of mouse events

Mouse events refer to events associated with mouse, inherited MouseEventinterface. Specific events mainly in the following.

  • click: Triggered when the mouse is pressed (usually by pressing the main button).
  • dblclick: Triggered when double-clicking the mouse on the same element.
  • mousedown: Triggered when the mouse button is pressed.
  • mouseup: Trigger release the mouse button pressed.
  • mousemove: Triggered when the mouse moves within a node. When the mouse continues to move, the event will trigger continuously. To avoid performance problems, it is recommended to do some limited function of the listening events, such as limited only run once over a period of time.
  • mouseenter: When the mouse enters a trigger node, enter the sub-node does not trigger this event (more on this later).
  • mouseover: When the mouse enters a trigger node, enter the sub-node will once again trigger this event (more on this later).
  • mouseout: A node when the mouse leaves the trigger, leaving the parent will trigger this event (more on this later).
  • mouseleave: A node when the mouse leaves the trigger, leaving the parent does not trigger this event (more on this later).
  • contextmenuWhen triggered by pressing the right mouse button (context menu appears before) trigger, or press the "context menu key":
  • wheel: When scrolling the mouse wheel to trigger the event inherited WheelEventinterface.

clickEvent means that the user to complete in the same position mousedownaction, and then complete the mouseupaction. Therefore, the order is triggered, mousedowntriggered first, mouseupthen trigger clickthe final trigger.

dblclickEvent is in mousedown, mouseup, clickafter triggering.

mouseoverEvents and mouseenterevents are triggered when the mouse enters a node. The difference is that mouseenterthe event is triggered only once, as long as the mouse moves inside the node, mouseoveran event will trigger multiple times on the child node.

/* HTML 代码如下
 <ul>
   <li>item 1</li>
   <li>item 2</li>
  <li>item 3</li>
 </ul>
*/

var ul = document.querySelector('ul');

// 进入 ul 节点以后,mouseenter 事件只会触发一次
// 以后只要鼠标在节点内移动,都不会再触发这个事件
// event.target 是 ul 节点
ul.addEventListener('mouseenter', function (event) {
  event.target.style.color = 'purple';
  setTimeout(function () {
    event.target.style.color = '';
  }, 500);
}, false);

// 进入 ul 节点以后,只要在子节点上移动,mouseover 事件会触发多次
// event.target 是 li 节点
ul.addEventListener('mouseover', function (event) {
  event.target.style.color = 'orange';
  setTimeout(function () {
    event.target.style.color = '';
  }, 500);
}, false);

The above code, enter the child within the parent node, will not trigger mouseenteran event, but triggers the mouseoverevent.

mouseoutEvents and mouseleaveevents are triggered when the mouse leaves a node. The difference is that when you leave a child element within the parent element, mouseleavethe event does not trigger, and mouseoutevent triggers.

/* HTML 代码如下
 <ul>
   <li>item 1</li>
   <li>item 2</li>
  <li>item 3</li>
 </ul>
*/

var ul = document.querySelector('ul');

// 先进入 ul 节点,然后在节点内部移动,不会触发 mouseleave 事件
// 只有离开 ul 节点时,触发一次 mouseleave
// event.target 是 ul 节点
ul.addEventListener('mouseleave', function (event) {
  event.target.style.color = 'purple';
  setTimeout(function () {
    event.target.style.color = '';
  }, 500);
}, false);

// 先进入 ul 节点,然后在节点内部移动,mouseout 事件会触发多次
// event.target 是 li 节点
ul.addEventListener('mouseout', function (event) {
  event.target.style.color = 'orange';
  setTimeout(function () {
    event.target.style.color = '';
  }, 500);
}, false);

The code above, inside the parent left child node, will not trigger mouseleavean event, but triggers the mouseoutevent.

MouseEvent Interface Overview

MouseEventInterface represents an event related to mouse click (click), double-click (dblclick), release the mouse button (mouseup), press the mouse button (mousedown) and other movements, the event object is generated MouseEventinstances. In addition, the event also drag wheel events and MouseEventinstances.

MouseEventInterface extends Eventthe interface, therefore, have Eventall the attributes and methods. It also has its own properties and methods.

Native browser provides a MouseEventconstructor to create a new MouseEventinstance.

var event = new MouseEvent(type, options);

MouseEventConstructor takes two parameters. The first argument is a string representing the name of the event; event second parameter is a configuration object, the parameter is optional. In addition Eventexample of a configuration attribute of the interface, the object can configure the following properties, all properties are optional.

  • screenX: The value, the mouse relative to the horizontal position (in pixels) of the screen, the default value is 0, provided that the property does not move the mouse.
  • screenY: The value, the position of the mouse relative to the vertical (in pixels) of the screen, and the other screenXthe same.
  • clientX: The value, the mouse relative to the horizontal position (in pixels) of the window, the default value is 0, provided that the property does not move the mouse.
  • clientY: The value, the position of the mouse relative to the vertical (in pixels) of the window, the other with clientXthe same.
  • ctrlKey: Boolean value, whether while pressing the Ctrl key, the default value false.
  • shiftKey: Boolean value, whether while pressing the Shift key, the default value false.
  • altKey: Boolean value, whether the Alt key while pressing the default value false.
  • metaKey: Boolean value, whether the Meta key while pressing the default value false.
  • button: Value, which represents the mouse button is pressed, a default value 0representing the primary key is pressed (usually the left mouse button), or the current event is not defined attribute; 1represents a secondary key is pressed (usually the middle mouse button), 2means to press the secondary key (usually the right mouse button).
  • buttons: Value, which pressed the mouse button, a three bit binary value to the default 0(no key is pressed). 1(Binary 001) indicates the primary key is pressed (usually the left), 2(binary 010) indicates a secondary key is pressed (usually the right), 4(binary 100) represents a secondary key is pressed (usually the middle button). Therefore, if the return 3(binary 011) says while pressing the left and right buttons.
  • relatedTarget: Node object that represents a node associated events, by default null. mouseenterAnd mouseoverwhen an event indicates that the element nodes mouse just left; mouseoutand mouseleavewhen an event indicates that the mouse is entering the element node.

Below is an example.

function simulateClick() {
  var event = new MouseEvent('click', {
    'bubbles': true,
    'cancelable': true
  });
  var cb = document.getElementById('checkbox');
  cb.dispatchEvent(event);
}

The above code generates a mouse click events, and triggers the event.

Examples of attributes of the interface MouseEvent

MouseEvent.altKey,MouseEvent.ctrlKey,MouseEvent.metaKey,MouseEvent.shiftKey

MouseEvent.altKey, MouseEvent.ctrlKey, MouseEvent.metaKey, MouseEvent.shiftKeyFour property returns a Boolean value that indicates when an event occurs, whether press the corresponding key. They are read-only attribute.

  • altKeyProperties: Alt key
  • ctrlKeyProperties: Ctrl key
  • metaKeyProperties: Meta key (Mac keyboard is a four flowers, Windows keyboard is the Windows key)
  • shiftKeyProperties: Shift key
// HTML 代码如下
// <body onclick="showKey(event)">
function showKey(e) {
  console.log('ALT key pressed: ' + e.altKey);
  console.log('CTRL key pressed: ' + e.ctrlKey);
  console.log('META key pressed: ' + e.metaKey);
  console.log('SHIFT key pressed: ' + e.shiftKey);
}

In the above code, click on the page will be output if the corresponding key press.

MouseEvent.button,MouseEvent.buttons

MouseEvent.buttonProperty returns a value indicating which key was pressed the mouse when the event occurs. This property is read-only.

  • 0: Press the primary key (usually the left), or does not initialize the event attributes (such mousemoveevents).
  • 1: Press the secondary key (typically a button or a wheel button).
  • 2: Press the next button (usually the right).
// HTML 代码为
// <button onmouseup="whichButton(event)">点击</button>
var whichButton = function (e) {
  switch (e.button) {
    case 0:
      console.log('Left button clicked.');
      break;
    case 1:
      console.log('Middle button clicked.');
      break;
    case 2:
      console.log('Right button clicked.');
      break;
    default:
      console.log('Unexpected code: ' + e.button);
  }
}

MouseEvent.buttonsProperty returns a value of three bits, which represents a key press. It is used to handle multiple presses on the mouse button. This property is read-only.

  • 1: Binary for the 001(decimal 1) indicates that pressing the left button.
  • 2: binary system 010(decimal 2), represents the right press.
  • 4: binary system 100(decimal 4) indicates that pressing the button or the wheel button.

When several keys, each key pressed there will be a corresponding bit value. For example, while pressing the left and right, returns 3 (binary 011).

MouseEvent.clientX,MouseEvent.clientY

MouseEvent.clientXProperty returns the mouse relative to the horizontal coordinate of the upper left corner position of the browser window (in pixels), MouseEvent.clientYproperty returns the vertical coordinate. These two properties are read-only attribute.

// HTML 代码为
// <body onmousedown="showCoords(event)">
function showCoords(evt){
  console.log(
    'clientX value: ' + evt.clientX + '\n' +
    'clientY value: ' + evt.clientY + '\n'
  );
}

These two properties are also have an alias MouseEvent.xand MouseEvent.y.

MouseEvent.movementX,MouseEvent.movementY

MouseEvent.movementXProperty returns a current location of the mousemovehorizontal distance between the event (in pixels). The value, which is equal to the following calculation formula.

currentEvent.movementX = currentEvent.screenX - previousEvent.screenX

MouseEvent.movementYProperty returns the current location on a mousemovevertical distance (in pixels) between events. The value, which is equal to the following calculation formula.

currentEvent.movementY = currentEvent.screenY - previousEvent.screenY。

These two properties are read-only attribute.

MouseEvent.screenX,MouseEvent.screenY

MouseEvent.screenXProperty returns the mouse relative to the horizontal coordinate of the top left position of the screen (in pixels), MouseEvent.screenYproperty returns the vertical coordinate. These two properties are read-only attribute.

// HTML 代码如下
// <body onmousedown="showCoords(event)">
function showCoords(evt) {
  console.log(
    'screenX value: ' + evt.screenX + '\n',
    'screenY value: ' + evt.screenY + '\n'
  );
}

MouseEvent.offsetX,MouseEvent.offsetY

MouseEvent.offsetXProperty returns the mouse position and the target node the left paddingedge of the horizontal distance (in pixels), MouseEvent.offsetYthe attribute with the destination node returns above the paddingvertical distance from the edge. These two properties are read-only attribute.

/* HTML 代码如下
  <style>
    p {
      width: 100px;
      height: 100px;
      padding: 100px;
    }
  </style>
  <p>Hello</p>
*/
var p = document.querySelector('p');
p.addEventListener(
  'click',
  function (e) {
    console.log(e.offsetX);
    console.log(e.offsetY);
  },
  false
);

The above code, if the mouse pclick on the center position of the element, will return 150 150. Thus from the left side and the center position of the top paddingedge, it is equal to paddingthe width (100 pixels) plus half the width (50 pixels) element content area.

MouseEvent.pageX,MouseEvent.pageY

MouseEvent.pageXProperty returns the mouse position from the left edge of the document (in pixels), MouseEvent.pageYproperty returns from the side edge of the document (in pixels). Their return value including documents invisible part. Both properties are read-only.

/* HTML 代码如下
  <style>
    body {
      height: 2000px;
    }
  </style>
*/
document.body.addEventListener(
  'click',
  function (e) {
    console.log(e.pageX);
    console.log(e.pageY);
  },
  false
);

In the above code, the page height of 2000 pixels, the vertical scroll bar is generated. Scroll to the bottom of the page, click on the mouse output pageYvalue will be close to 2,000.

MouseEvent.relatedTarget

MouseEvent.relatedTargetProperty returns the node associated events. For those events not associated nodes, this property returns null. This property is read-only.

The following table lists the different events of targetproperty values and relatedTargetproperty values justice.

Event Name The target property relatedTarget property
focusin Node receiving focus Loss of focus node
focusout Loss of focus node Node receiving focus
mouseenter To enter the node Node is going to leave
mouseleave Node is going to leave To enter the node
mouseout Node is going to leave To enter the node
mouseover To enter the node Node is going to leave
dragenter To enter the node Node is going to leave
dragexit Node is going to leave To enter the node

Below is an example.

/*
  HTML 代码如下
  <div id="outer" style="height:50px;width:50px;border-width:1px solid black;">
    <div id="inner" style="height:25px;width:25px;border:1px solid black;"></div>
  </div>
*/

var inner = document.getElementById('inner');
inner.addEventListener('mouseover', function (event) {
  console.log('进入' + event.target.id + ' 离开' + event.relatedTarget.id);
}, false);
inner.addEventListener('mouseenter', function (event) {
  console.log('进入' + event.target.id + ' 离开' + event.relatedTarget.id);
});
inner.addEventListener('mouseout', function () {
  console.log('离开' + event.target.id + ' 进入' + event.relatedTarget.id);
});
inner.addEventListener("mouseleave", function (){
  console.log('离开' + event.target.id + ' 进入' + event.relatedTarget.id);
});

// 鼠标从 outer 进入inner,输出
// 进入inner 离开outer
// 进入inner 离开outer

// 鼠标从 inner进入 outer,输出
// 离开inner 进入outer
// 离开inner 进入outer

Examples of the method MouseEvent interface

MouseEvent.getModifierState()

MouseEvent.getModifierStateMethod returns a Boolean value indicating there is no pressing a particular function key. Its parameters are represented by a function key string.

document.addEventListener('click', function (e) {
  console.log(e.getModifierState('CapsLock'));
}, false);

The above code can understand the user has pressed the caps lock.

WheelEvent Interface

Outline

WheelEvent interface extends MouseEvent instance, the instance object represents the mouse wheel event. Currently, mouse wheel events associated with only one wheelevent, the user scrolls the mouse wheel, you create an instance of this event.

Native browser provided WheelEvent()constructor to generate WheelEventinstances.

var wheelEvent = new WheelEvent(type, options);

WheelEvent()The constructor can accept two arguments, the first is the string representing the type of event, for wheel events, this value can only be wheel. The second parameter is the configuration object events. Properties of the object in addition to Event, UIEventother than the configuration properties, the following properties may also be acceptable, all the attributes are optional.

  • deltaX: Value indicates the amount of horizontal scrolling wheel, the default value is 0.0.
  • deltaY: Value indicates the amount of vertical scrolling wheel, the default value is 0.0.
  • deltaZ: The value representing the amount of wheel rolling axis Z, the default value is 0.0.
  • deltaMode: Value that represents the unit of the underlying rolling event for the top three attributes. 0Scroll expressed in pixels, 1expressed in units of lines, 2expressed in units of pages, by default 0.

Instance Properties

WheelEventIn addition to the event instance Eventand MouseEventinstance properties and instance methods, there are some examples of their own property, but does not own an instance method.

The following properties are read-only attribute.

  • WheelEvent.deltaX: Value indicates the amount of horizontal scrolling wheel.
  • WheelEvent.deltaY: Value indicates the amount of vertical scrolling wheel.
  • WheelEvent.deltaZ: Value, the Z-axis indicates the amount of rolling of the roller.
  • WheelEvent.deltaMode: Value represents a unit of the above three attributes, 0pixels, 1a row, 2a page.

Guess you like

Origin www.cnblogs.com/wbyixx/p/12499300.html