JavaScript HTML DOM 事件示例
使用 JavaScript 响应事件的示例
1.输入事件
1. onblur-当用户离开输入字段时
<!DOCTYPE html> <html> <head> <script> function myFunction() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="myFunction()"> <p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p> </body> </html>
2. onchange-当用户更改输入字段的内容时
<!DOCTYPE html> <html> <body> <h2>JavaScript HTML Events</h2> Enter your name: <input type="text" id="fname" onchange="upperCase()"> <p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p> <script> function upperCase() { const x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> </body> </html>
3. onchange-当用户选择下拉值时
<!DOCTYPE html> <html> <head> <script> function preferedBrowser() { prefer = document.forms[0].browsers.value; alert("You prefer browsing internet with " + prefer); } </script> </head> <body> <form> Choose which browser you prefer: <select id="browsers" onchange="preferedBrowser()"> <option value="Chrome">Chrome</option> <option value="Internet Explorer">Internet Explorer</option> <option value="Firefox">Firefox</option> </select> </form> </body> </html>
4. onfocus-当输入字段获得焦点时
<!DOCTYPE html> <html> <head> <script> function myFunction(x) { x.style.background = "yellow"; } </script> </head> <body> Enter your name: <input type="text" onfocus="myFunction(this)"> <p>When the input field gets focus, a function is triggered which changes the background-color.</p> </body> </html>
5. onselect-选择输入文本时
<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "You selected some text"; } </script> </head> <body> Some text: <input type="text" value="Hello world!" onselect="myFunction()"> <p id="demo"></p> </body> </html>
6. onsubmit-当用户单击提交按钮时
<!DOCTYPE html> <html> <head> <script> function confirmInput() { fname = document.forms[0].fname.value; alert("Hello " + fname + "! You will now be redirected to www.w3Schools.com"); } </script> </head> <body> <form onsubmit="confirmInput()" action="https://www.w3schools.com/"> Enter your name: <input id="fname" type="text" size="20"> <input type="submit"> </form> </body> </html>
7. onreset-当用户点击重置时
<!DOCTYPE html> <html> <head> <script> function message() { alert("This alert box was triggered by the onreset event handler"); } </script> </head> <body> <form onreset="message()"> Enter your name: <input type="text" size="20"> <input type="reset"> </form> </body> </html>
8. onkeydown-当用户按下/按住一个键时
<!DOCTYPE html> <html> <head> <script> function myFunction() { alert("You pressed a key inside the input field"); } </script> </head> <body> <p>A function is triggered when the user is pressing a key in the input field.</p> <input type="text" onkeydown="myFunction()"> </body> </html>
9. onkeypress-当用户按下/按住一个键时
<!DOCTYPE html> <html> <head> <script> function myFunction() { alert("You pressed a key inside the input field"); } </script> </head> <body> <p>A function is triggered when the user is pressing a key in the input field.</p> <input type="text" onkeypress="myFunction()"> </body> </html>
10. onkeyup-当用户稀放一个键时
<!DOCTYPE html> <html> <head> <script> function myFunction() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> </head> <body> <p>A function is triggered when the user releases a key in the input field. The function transforms the character to upper case.</p> Enter your name: <input type="text" id="fname" onkeyup="myFunction()"> </body> </html>
11. onkeyup-当用户稀放一个键时
<!DOCTYPE html> <html> <head> <script> function writeMessage() { document.forms[0].mySecondInput.value = document.forms[0].myInput.value; } </script> </head> <body> <p>The onkeyup event occurs when the a keyboard key is on its way UP.</p> <form> Enter your name: <input type="text" name="myInput" onkeyup="writeMessage()" size="20"> <input type="text" name="mySecondInput" size="20"> </form> </body> </html>
12. onkeydown与onkeyup-两者
<!DOCTYPE html> <html> <head> <script> function color(color) { document.forms[0].myInput.style.background = color; } </script> </head> <body> <form> Write a message:<br> <input type="text" onkeydown="color('yellow')" onkeyup="color('white')" name="myInput"> </form> </body> </html>
2.鼠标事件
1. onmouseover/onmouseout-当鼠标经过一个元素
<!DOCTYPE html> <html> <body> <h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1> </body> </html>
2. onmousedown/onmouseup-按下/稀放鼠标按钮时
<!DOCTYPE html> <html> <head> <script> function myFunction(elmnt, clr) { elmnt.style.color = clr; } </script> </head> <body> <p onmousedown="myFunction(this,'red')" onmouseup="myFunction(this,'green')"> Click the text to change the color. A function, with parameters, is triggered when the mouse button is pressed down, and again, with other parameters, when the mouse button is released. </p> </body> </html>
3. onmousedown-单击鼠标时:提示哪个元素
<!DOCTYPE html> <html> <head> <script> function whichElement(e) { var targ; if (!e) { var e = window.event; } if (e.target) { targ=e.target; } else if (e.srcElement) { targ=e.srcElement; } var tname; tname = targ.tagName; alert("You clicked on a " + tname + " element."); } </script> </head> <body onmousedown="whichElement(event)"> <p>Click somewhere in the document. An alert box will alert the name of the element you clicked on.</p> <h3>This is a heading</h3> <img border="0" src="smiley.gif" alt="Smiley" width="32" height="32"> <p>This is a paragraph.</p> </body> </html>
4. onmousedown-单击鼠标时:提示哪个按钮
<!DOCTYPE html> <html> <head> <script> function WhichButton(event) { alert("You pressed button: " + event.button) } </script> </head> <body> <div onmousedown="WhichButton(event);">Click this text (with one of your mouse-buttons) <p> 0 Specifies the left mouse-button<br> 1 Specifies the middle mouse-button<br> 2 Specifies the right mouse-button</p> <p><strong>Note:</strong> Internet Explorer 8, and earlier, returns another result:<br> 1 Specifies the left mouse-button<br> 4 Specifies the middle mouse-button<br> 2 Specifies the right mouse-button</p> </div> </body> </html>
5. onmousemove/onmouseout-将鼠标指针移出/移出图像时
<!DOCTYPE html> <html> <head> <script> function myFunction(e) { x = e.clientX; y = e.clientY; coor = "Coordinates: (" + x + "," + y + ")"; document.getElementById("demo").innerHTML = coor } function clearCoor() { document.getElementById("demo").innerHTML = ""; } </script> </head> <body style="margin:0px;"> <div id="coordiv" style="width:199px;height:99px;border:1px solid" onmousemove="myFunction(event)" onmouseout="clearCoor()"></div> <p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p> <p id="demo"></p> </body> </html>
6. onmouseover/onmouseout-将鼠标移出/移出图片时
<!DOCTYPE html> <html> <head> <script> function bigImg(x) { x.style.height = "64px"; x.style.width = "64px"; } function normalImg(x) { x.style.height = "32px"; x.style.width = "32px"; } </script> </head> <body> <img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif" alt="Smiley" width="32" height="32"> <p>The function bigImg() is triggered when the user moves the mouse pointer over the image.</p> <p>The function normalImg() is triggered when the mouse pointer is moved out of the image.</p> </body> </html>
7. 鼠标悬停在图像地图上
<!DOCTYPE html> <html> <head> <script> function writeText(txt) { document.getElementById("desc").innerHTML = txt; } </script> </head> <body> <img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" /> <map name="planetmap"> <area shape ="rect" coords ="0,0,82,126" onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by far the largest objects in our Solar System.')" href ="sun.htm" target ="_blank" alt="Sun" /> <area shape ="circle" coords ="90,58,3" onmouseover="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')" href ="mercur.htm" target ="_blank" alt="Mercury" /> <area shape ="circle" coords ="124,58,8" onmouseover="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')" href ="venus.htm" target ="_blank" alt="Venus" /> </map> <p id="desc">Mouse over the sun and the planets and see the different descriptions.</p> </body> </html>
3.点击事件
1. 作用于onclick事件
<!DOCTYPE html> <html> <head> <script> function displayDate() { document.getElementById("demo").innerHTML = Date(); } </script> </head> <body> <h2>My First JavaScript</h2> <p id="demo">This is a paragraph.</p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html>
2. onclick-单击按钮时
<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; } </script> </head> <body> <p>Click the button to trigger a function.</p> <button onclick="myFunction()">Click me</button> <p id="demo"></p> </body> </html>
3. ondbclick-双击文本时
<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; } </script> </head> <body> <p ondblclick="myFunction()">Doubleclick this paragraph to trigger a function.</p> <p id="demo"></p> </body> </html>
4.加载事件
1.onload-当页面被加载时
<!DOCTYPE html> <html> <head> <script> function myFunction() { alert("Page is loaded"); } </script> </head> <body onload="myFunction()"> <h2>Hello World!</h2> </body> </html>
2.onload-加载图片时
<!DOCTYPE html> <html> <head> <script> function loadImage() { alert("Image is loaded"); } </script> </head> <body> <img src="w3javascript.gif" onload="loadImage()" width="100" height="132"> </body> </html>
3.onerror-当加载图像时发生错误
<!DOCTYPE html> <html> <head> <script> function imgError() { alert('The image could not be loaded.'); } </script> </head> <body> <img src="image.gif" onerror="imgError()"> <p>A function is triggered if an error occurs when loading the image. The function shows an alert box with a text. In this example we refer to an image that does not exist, therefore the onerror event occurs.</p> </body> </html>
4.onunload-当浏览器关闭文档时
<!DOCTYPE html> <html> <head> <script> function myFunction() { alert("Thank you for visiting W3Schools!"); } </script> </head> <body onunload="myFunction()"> <h2>Welcome to my Home Page</h2> <p>Close this window or press F5 to reload the page.</p> </body> </html>
5.onresize-调整浏览器窗口大小时
<!DOCTYPE html> <html> <head> <script> function myFunction() { var w = window.outerWidth; var h = window.outerHeight; var txt = "Window size: width=" + w + ", height=" + h; document.getElementById("demo").innerHTML = txt; } </script> </head> <body onresize="myFunction()"> <p>Try to resize the browser window.</p> <p id="demo"> </p> <p>Note: this example will not work properly in IE8 and earlier. IE8 and earlier do not support the outerWidth/outerHeight propery of the window object.</p> </body> </html>
5.其他
1. 按下的键的键码是什么?
<!DOCTYPE html> <html> <head> <script> function whichButton(event) { document.getElementById("demo").innerHTML = event.keyCode; } </script> </head> <body onkeyup="whichButton(event)"> <p><b>Note:</b> Make sure the right frame has focus when trying this example!</p> <p>Click on this page, and press a key on your keyboard.</p> <p id="demo"></p> </body> </html>
2. 光标的坐标是多少?
<!DOCTYPE html> <html> <head> <script> function show_coords(event) { document.getElementById("demo").innerHTML = "X= " + event.clientX + "<br>Y= " + event.clientY; } </script> </head> <body> <p onmousedown="show_coords(event)"> Click this paragraph to display the x and y coordinates of the mouse pointer.</p> <p id="demo"></p> </body> </html>
3. 光标相对于屏幕的坐标是多少?
<!DOCTYPE html> <html> <head> <script> function coordinates(event) { document.getElementById("demo").innerHTML = "X = " + event.screenX + "<br>Y = " + event.screenY; } </script> </head> <body> <p onmousedown="coordinates(event)"> Click this paragraph, to display the x and y coordinates of the cursor, relative to the screen. </p> <p id="demo"></p> </body> </html>
4. 是否按下了shift键?
<!DOCTYPE html> <html> <head> <script> function isKeyPressed(event) { var text = "The shift key was NOT pressed!"; if (event.shiftKey == 1) { text = "The shift key was pressed!"; } document.getElementById("demo").innerHTML = text; } </script> </head> <body onmousedown="isKeyPressed(event)"> <p>Click on this paragraph. An alert box will tell you if you pressed the shift key or not.</p> <p id="demo"></p> </body> </html>
5. 发生了哪种事件类型?
<!DOCTYPE html> <html> <head> <script> function getEventType(event) { document.getElementById("demo").innerHTML = event.type; } </script> </head> <body> <p onmousedown="getEventType(event)"> Click on this paragraph. A message will tell what type of event was triggered.</p> <p id="demo"></p> </body> </html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现