Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize keyboard and mouse events in JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

In this article, Xiaobian introduces in detail how to achieve keyboard and mouse events in JavaScript, with detailed content, clear steps and proper handling of details. I hope that this article "how to achieve keyboard and mouse events in JavaScript" can help you solve your doubts.

Page event

Think about it: in what order are HTML pages loaded?

Answer: the page is loaded in the order in which the code is written, from top to bottom.

The problem: if you use JavaScript to manipulate the DOM element before the page has finished loading, a syntax error will occur.

Solution: page events can change the timing of JavaScript code execution.

Load event: used to trigger after all the tags in the body have been loaded, and because it does not need to consider the loading order of the page, it is often added when developing specific features.

Unload event: used to trigger when a page is closed and is often used to clear references to avoid memory leaks.

Focus event

In Web development, focus events are mostly used for form validation, which is one of the most commonly used events.

For example, the text box gets focus to change the style of the text box, validate the data entered in the text box when the text box loses focus, and so on.

In order to give you a better understanding of the use of focus events, the following is a demonstration to verify that the user name and password are empty.

Code implementation

Verify that the username and password are empty body {background:#ddd;} .box {background:#fff;padding:20px 30pxwitWidthbank 400pxleft margin: 0 auto;text-align:center;} .btn {width:180px;height:40px;background:#3388ff;border:1px solid # fff;color:#fff;font-size:14px;} .ipt {width:260px;padding:4px 2px;} .tips {width:440px;height:30px Margin:5px auto;background:#fff;color:red;border:1px solid # ccc;display:none;line-height:30px;padding-left:20px;font-size:13px;}

User name:

Secret code:

Log in

_ window.onload = function () {addBlur ($('user')); / / detects whether the value value is empty addBlur ($(' pass')) after the element whose id is user loses focus; / / detects whether the value value is empty} after the element whose id is pass loses focus; function $(obj) {/ / gets the specified element return document.getElementById (obj) according to id } function addBlur (obj) {/ / add a loss of focus event for the specified element obj.onblur = function () {isEmpty (this);};} function isEmpty (obj) {/ / detect whether the form is empty if (obj.value = ='') {$('tips'). Style.display =' block' $('tips') [xss_clean] =' Note: input cannot be empty!';} else {$('tips'). Style.display =' none';}} mouse event

Mouse events are the most commonly used events in Web development.

For example, when the mouse is over, toggle the content displayed in the Tab bar; drag the status box with the mouse, adjust its display position, and so on, these common web page effects will use mouse events.

Some commonly used mouse properties are often involved in project development, which are used to obtain the current mouse location information.

The pageX and pageY properties are not compatible in IE6-8 browsers. Therefore, the project development needs to be compatible with IE6~8 browsers.

The coordinates of the mouse in the document are equal to the coordinates of the mouse in the current window plus the length of the text scrolled away by the scroll bar.

In order to give you a better understanding of the use of mouse events, take the circular display of the mouse click position as an example.

Code implementation

Displays the mouse click position .mouse {position:absolute;background:#ffd965;width:40px;height:40px;border-radius:20px;}

Var mouse = document.getElementById ('mouse'); / / demand: when the mouse clicks on the page, it gets the location of the click and displays a dot _ document.onclick = function (event) {/ / get the compatible handling of the event object var event = event | | window.event; / / mouse position on the page var pageX = event.pageX | | event.clientX + document.documentElement.scrollLeft Var pageY = event.pageY | | event.clientY + document.documentElement.scrollTop; / / calculation

The location that should be displayed var targetX = pageX-mouse.offsetWidth / 2; var targetY = pageY-mouse.offsetHeight / 2; / / where the mouse is clicked

Mouse.style.display = 'block'; mouse.style.left = targetX +' px'; mouse.style.top = targetY + 'px';}

[case] mouse drag special effect

Location of the box (left and top values) = position of the mouse (left and top values)-the distance between the box and the box when the mouse is pressed (left and top values).

For instance

Code implementation ideas:

① writes HTML and designs bullet boxes to achieve drag-and-drop effects.

② adds a mousedown event and its handler to the drag bar.

③ handles mouse movement events to achieve the special effect of mouse drag and drop.

④ handles the event of releasing the mouse button, so that after the mouse button is released, the pop-up box no longer moves.

Code implementation

Drag the mouse body {margin:0} .box {width:400px;height:300px;border:5px solid # eee;box-shadow:2px 2px 2px 2px # 666 position cross topside 30% bot leftfrog 30% width:100%;height:25px;background-color:#7c9299;border-bottom:1px solid # 369 th lineheightRod 25px colorside color color displacement cursormove # box_close {float:right Cursor:pointer} Registration Information (can be dragged) [off]

/ / get the dragged box and drag bar var box = document.getElementById ('box'); var drop = document.getElementById (' drop'); drop.onmousedown = function (event) {/ / Mouse press the draggable box var event = event | | window.event; / / get the position var pageX = event.pageX when the mouse is pressed | | event.clientX + document.documentElement.scrollLeft Var pageY = event.pageY | | event.clientY + document.documentElement.scrollTop; / / calculate the position of the mouse pressed from the box var spaceX = pageX-box.offsetLeft; var spaceY = pageY-box.offsetTop; _ document.onmousemove = function (event) {/ / get the position of the mouse when the mouse moves the whole box follows the position of the mouse var event = event | | window.event / / get the mouse position after moving var pageX = event.pageX | | event.clientX + document.documentElement.scrollLeft; var pageY = event.pageY | | event.clientY + document.documentElement.scrollTop; / / calculate and set the position of the box after moving box.style.left = pageX-spaceX + 'px'; box.style.top = pageY-spaceY +' px';};} _ document.onmouseup = function () {/ / cancel the movement of the box when the mouse button is released _ document.onmousemove = null;}; keyboard event

Keyboard events are events that are triggered by the user when using the keyboard.

For example, the user presses the ESC key to close the open status bar and presses the enter key to switch the cursor up and down directly.

The following is demonstrated by the use of Enter key toggle. As shown in the example.

Code implementation

Press Enter to switch

User name:

Email address:

Mobile phone number:

Personal description:

Var inputs = document.getElementsByTagName ('input'); for (var I = 0; I

< inputs.length; ++i) { inputs[i].onkeydown = function(e) { // 获取事件对象的兼容处理 var e = event || window.event; // 判断按下的是不是回车,如果是,让下一个input获取焦点 if (e.keyCode === 13) { // 遍历所有input框,找到当前input的下标 for (var i = 0; i < inputs.length; ++i) { if (inputs[i] === this) { // 计算下一个input元素的下标 var index = i + 1 >

= inputs.length? 0: I + 1; break;}} / / if the next input is a text box, get the keyboard focus if (inputs [index] .type = = 'text') {inputs [index] .focus (); / trigger focus event};}

Be careful

The key value saved by the keypress event is an ASCII code.

The keystroke values saved by the keydown and keyup events are virtual keys.

Refer to MDN and other manuals.

Form event

Form events refer to events that occur when you operate on an Web form.

For example, the validation of the form before submission, the confirmation action when the form is reset, and so on. JavaScript provides relevant form events.

The following is an example of whether to submit and reset form data. As shown in the example.

Code implementation

Form event username: / / get the form and the element object to be validated var regist = document.getElementById ('register'); var user = document.getElementById (' user') Regist.onsubmit = function (event) {/ / add submit event to the form / / get the event object, output the current event type var event = event | | window.event; console.log (event.type); / / determine whether the content of the form element is empty, if it is empty, return false, otherwise return true return user.value? True: false;}; regist.onreset = function (event) {/ / add a reset event to the form / / get the event object and output the current event type var event = event | | window.event; console.log (event.type) / / decide whether to confirm the reset, press "OK" to return to true, press "cancel" to return to false return confirm ('Please confirm whether you want to reset the information, after the reset, all the contents of the form will be emptied');}

Hands-on practice

Picture magnification special effect

Analyze how to achieve image magnification effects:

① prepares two identical pictures, small and large.

The small picture of ② is displayed in the display area of the goods.

The ③ large image is used to display the corresponding area in the large image proportionally when the mouse is moved over the small image.

Code implementation ideas:

① writes HTML pages that show small images, hidden mouse masks and large images.

② displays the mask and large image of the mouse when the mouse is moved over the small image.

③ when the mouse moves, let the mask follow and move in the small image.

④ limits the range of movement masked in the small image.

⑤ displays the larger image proportionally according to the coverage of the mask in the small image.

After reading this, the article "how to realize keyboard and mouse events in JavaScript" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report