JavaScript 事件

2021-08-27 15:22 更新

事件

事件是什么?

JavaScriptHTML 的交互是通過事件來處理的,當用戶或瀏覽器操縱頁面時。事件就會發(fā)生。

當頁面加載時,這是一個事件。當用戶單擊一個按鈕,點擊,是一個事件。另一個例子:事件就像按任何鍵,關閉窗口,調整窗口等。

開發(fā)人員可以使用這些事件來執(zhí)行 JavaScript 編碼的響應,如導致按鈕關閉窗口,信息顯示給用戶,數據驗證,和任何其他類型的反應的發(fā)生。

事件都是文檔對象模型(DOM)三級的一部分,并且每個HTML元素有一定的事件可以觸發(fā) JavaScript 代碼。

請通過這個小教程為更好地理解 HTML 事件參考。這里我們將看到一些例子來理解事件和 JavaScript 之間的關系:

onclick 事件類型

這是最常用的事件類型,當用戶點擊鼠標左按鈕。你可以把你的驗證、警告等反對這個事件類型。

例子

<html>
    <head>
    <script type="text/javascript">
        function sayHello() {
            alert("Hello World")
        }
    </script>
    </head>
    <body>
        <input type="button" onclick="sayHello()" value="Say Hello" />
    </body>
</html>  

它將產生以下結果:當你點擊Say Hello按鈕 onclick 事件將發(fā)生,將觸發(fā) sayHello() 函數,彈出一個hello world的消息彈窗。

onsubmit 事件類型

另一個最重要的是 onsubmit 事件類型。這個事件發(fā)生在您嘗試提交一個表單。所以你可以用此事件類型進行表單驗證。

下面一個簡單簡單的例子顯示其用法。我們在這里調用 validate() 函數之前提交表單數據到網絡服務器。如果 validate() 函數返回 true 表單將提交否則不會提交數據。

例子

<html>
    <head>
    <script type="text/javascript">
    function validation() {
        all validation goes here
        .........
        return either true or false
    }
    </script>
    </head>
    <body>
        <form method="POST" action="t.cgi" onsubmit="return validate()">
            .......
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>  

onmouseover 和 onmouseout

這兩個事件類型將會幫助你創(chuàng)建好良好的圖像效果和文本事件。onmouseover 事件發(fā)生時,當你把你的鼠標在任何元素上時, onmouseover 事件發(fā)生。當你把鼠標從該元素移開時,onmouseout 事件發(fā)生。

例子

下面的例子顯示了一個部位如何反應當我們把鼠標在這個部位上:

<html>
    <head>
    <script type="text/javascript">
        function over() {
            alert("Mouse Over");
        }
        function out() {
           alert("Mouse Out");
        }
    </script>
    </head>
    <body>
        <div onmouseover="over()" onmouseout="out()">
            <h2> This is inside the division </h2>
        </div>
    </body>
</html>  

你可以改變不同的圖像使用這兩種事件類型或您可以創(chuàng)建幫助氣框,來幫助你的用戶。

HTML 4 標準事件

標準的 HTML 4 事件被列在這里,供您參考。執(zhí)行以下腳本顯示一個Javascript函數。

EventValueDescription
onchangescriptScript runs when the element changes
onsubmitscriptScript runs when the form is submitted
onresetscriptScript runs when the form is reset
onselectscriptScript runs when the element is selected
onblurscriptScript runs when the element loses focus
onfocusscriptScript runs when the element gets focus
onkeydownscriptScript runs when key is pressed
onkeypressscriptScript runs when key is pressed and released
onkeyupscriptScript runs when key is released
onclickscriptScript runs when a mouse click
ondblclickscriptScript runs when a mouse double-click
onmousedownscriptScript runs when mouse button is pressed
onmousemovescriptScript runs when mouse pointer moves
onmouseoutscriptScript runs when mouse pointer moves out of an element
onmouseoverscriptScript runs when mouse pointer moves over an element
onmouseupscriptScript runs when mouse button is released


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號