Mouse and keyboard event objects
mouse event object
The event object represents the state of the event and a collection of a series of information related to the event. At this stage we mainly use mouse event object MouseEvent and keyboard event object KeyboardEvent
For example:
// 鼠标事件对象 MouseEvent
document.addEventListener('click', function (e) {
// 1. client 鼠标在可视区(即不管屏幕是否发生滚动,参考只是窗口)的x和y坐标
console.log(e.clientX);
console.log(e.clientY);
console.log('---------------------');
// 2. page 鼠标在页面文档的x和y坐标
console.log(e.pageX);
console.log(e.pageY);
console.log('---------------------');
// 3. screen 鼠标在电脑屏幕的x和y坐标
console.log(e.screenX);
console.log(e.screenY);
})
Case: an angel that moves with the mouse
Implementation principle:
- The mouse moves continuously, use the mouse move event: mousemove
- Move in the page, register events for document
- The picture needs to move distance, and does not occupy the position, we can use absolute positioning
- Core principle: Every time the mouse moves, we will get the latest mouse coordinates, and use the x and y coordinates as the top and left values of the picture to move the picture
<body>
<div>
<img src="images/angel.gif" alt="">
</div>
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove', function(e) {
var x = e.pageX;
var y = e.pageY;
console.log('x坐标是' + x, 'y坐标是' + y);
//3 . 千万不要忘记给left 和top 添加px 单位
pic.style.left = x - 50 + 'px';
pic.style.top = y - 35 + 'px';
});
</script>
</body>
keyboard event object
Notice:
- If you use addEventListener, you don't need to add on
- The difference between onkeypress and the previous two is that it does not recognize function keys, such as left and right arrows, shift, etc.
- The execution order of the three events is: keydown 、 keypress 、 keyup
For example:
result:
Notice:
- onkeydown and onkeyup are case-insensitive, and onkeypress is case-sensitive.
- In actual development, more keydown and keyup are used, which can recognize all keys (including function keys)
- Keypress does not recognize function keys, but the keyCode property is case-sensitive and returns different ASCII values
Case: When we press the s key, the cursor is positioned in the search box
case analysis:
- Core idea: Detect whether the user has pressed the s key, and if the s key is pressed, position the cursor in the search box
- Use the keyCode in the keyboard event object to determine whether the user pressed the s key
- The search box gets the focus: use the focus() method in js
Effect: The effect is to automatically obtain the position of the input box after pressing s