JavaScript与HTML的交互是通过在用户或浏览器操纵页面时发生的事件来处理的。
页面加载时称为事件。当用户单击一个按钮时,该单击将是一个事件。其他示例包括事件,例如按下任意键,关闭窗口,调整窗口大小等。
这里有些例子:
onclick 事件类型
这是最常用的事件类型,当用户单击其鼠标左键时发生。您可以针对此事件类型进行验证,警告等。
请尝试以下示例。
<html> <head> <script> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body> </html>
鼠标悬停 和 鼠标悬停
这两种事件类型将帮助您使用图像甚至文本创建漂亮的效果。将鼠标移到任何元素上时会触发onmouseover事件,而将鼠标从该元素上移出时会触发onmouseout事件。请尝试以下示例。
<html> <head> <script> <!-- function over() { document.write ("Mouse Over"); } function out() { document.write ("Mouse Out"); } //--> </script> </head> <body> <p>Bring your mouse inside the division to see the result:</p> <div onmouseover="over()" onmouseout="out()"> <h2> This is inside the division </h2> </div> </body> </html>