On Javascript Event Object

  • 2021-07-16 01:23:29
  • OfStack

If it is a function bound by an event handler, the browser will pass 1 parameter by default, and this parameter is the event object.


document.onclick = function() {
 alert(arguments.length); //1
}

Because arguments [0] is troublesome to use this parameter, we can pass a parameter evt to use it.


document.onmouseup = function(evt) {
 var e = evt || window.event;
 alert(e.button); //0 Is the left mouse button, 1 For the roller, 2 Right-click 
 // Based on the position of the upper left corner of the browser viewable area 
 alert(e.clientX + ',' + e.clientY);
 // Resolution of a machine 
 alert(window.screen.width + ',' + window.screen.height);
 //  Position from the upper left corner of the screen 
 alert(e.screenX + ',' + e.screenY);
}

// Detecting button 
document.onclick = function(evt) {
 alert(getKey(evt));
}
function getKey(evt) {
 var e = evt || window.event;
 var keys = [];
 if (e.shiftKey) {
 keys.push('shift');
 }
 if (e.ctrlKey) {
 keys.push('ctrl');
 }
 if (e.altKey) {
 keys.push('alt');
 }
 return keys;
}

// Keyboard event ,keydown Is to press any key, keyup Is to pop up any key, keypress Press the character key to trigger 
// Key code: Any key on the keyboard , Full compatibility 
// Character encoding: The key of a character that can be output. IE Incompatible 
document.onkeydown=function(evt){
 var e = evt || window.event;
 alert(e.keyCode); //keyCode Return key code 
 }
document.onkeypress = function(evt) {
 var e = evt || window.event;
 alert(e.charCode);  //charCode Return character key code 
 }
document.onclick = function(evt) {
 var e = evt || window.event;
 alert(e.target.innerHTML);  // Where to Point target Which element is selected 
 }


Related articles: