HTML - DOM 元素 addEventListener() 方法



addEventListener() 方法允许开发者向元素注册事件处理程序,使元素能够响应用户的操作,例如点击或按键。

语法

 element.addEventListener(event, function, useCapture) 

参数

参数 描述
event 指定要监听的事件类型,例如 click、mouseover、keypress 等。
function 定义当指定事件发生时要执行的函数。
useCapture (可选) 确定事件处理阶段
- 如果为 true,则在捕获阶段执行事件处理程序。
- 如果为 false (默认),则在冒泡阶段执行事件处理程序。

返回值

addEventListener() 方法不返回值;而是将事件监听器附加到元素。

HTML DOM 元素 'addEventListener()' 方法示例

以下是一些示例,说明如何使用 addEventListener() 方法来处理各种 HTML DOM 元素上的事件。

点击事件监听器

此示例将点击事件监听器附加到按钮,在点击时触发操作。当有人点击按钮时,会弹出一个消息,显示“已点击按钮!”。

  
<!DOCTYPE html>
<html>

<head>
    <title>Click Event Example</title>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">addEventListener() Method
    <br><br>Click Event 
    </h3>
    <button id="myButton">Click me</button>

    <script>
        var button = document.getElementById('myButton');
        
        button.addEventListener('click', function() {
            alert('Button clicked!');
        });
    </script>
</body>

</html>

鼠标悬停事件监听器

此示例在鼠标悬停在 div 上时更改其背景颜色。尝试将鼠标移到方块上!它会变色!这就是 addEventListener() 的魔力。

<!DOCTYPE html>
<html>

<head>
    <title>Mouse Over Event Example</title>
    <style>
        .myDiv {
            width: 200px;
            height: 200px;
            background-color: lightgray;
        }
    </style>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">addEventListener() Method
    <br><br>Mouse Over Event
    </h3>
    <div class="myDiv" id="myDiv">Hover over me!</div>
    <script>
        var div = document.getElementById('myDiv');
        
        div.addEventListener('mouseover', function() {
            div.style.backgroundColor = 'lightblue';
        });

        div.addEventListener('mouseout', function() {
            div.style.backgroundColor = 'lightgray';
        });
    </script>
</body>

</html>

按键事件监听器

此示例在按下键盘上的键时显示按下的键。曾经想知道你按下了键盘上的哪个键吗?现在你可以用 addEventListener() 找出答案!按下键盘上的任何键,你都会看到一条消息告诉你按下了哪个键!

<!DOCTYPE html>
<html>

<head>
    <title>Key Press Event Example</title>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">addEventListener() Method
    <br><br>Key Press Event
    </h3>
    <p>Press any key.....</p>
    <script>
        document.body.addEventListener('keypress', function(event) {
            alert('You pressed the key: ' + event.key);
        });
    </script>
</body>

</html>

提交表单事件监听器

此示例阻止默认的表单提交行为,并显示包含输入用户名的消息框。填写你的姓名并点击“提交”。你会看到一条专属于你的友好消息!

<!DOCTYPE html>
<html>

<head>
    <title>Submit Form Event Example</title>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">addEventListener() Method
    <br><br>Submit Form Event
    </h3>
    <form id="myForm">
        <input type="text" name="username" placeholder="Enter your name">
        <button type="submit">Submit</button>
    </form>

    <script>
        document.getElementById('myForm').addEventListener('submit', function(event) {
            event.preventDefault();
            var username = event.target.elements.username.value;
            alert('Hello, ' + username + '! You submitted the form!');
        });
    </script>
</body>

</html>

更改事件监听器

此示例在下拉菜单中的选择更改时显示所选值。尝试从下拉菜单中选择不同的选项。每次更改选择时,都会出现一条消息告诉你选择了哪个选项!

<!DOCTYPE html>
<html>

<head>
    <title>Change Event Example</title>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">addEventListener() Method
    <br><br>Change Event
    </h3>
    <p>Please Select any Option...</p>
    <select id="mySelect">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
    </select>

    <script>
        document.getElementById('mySelect').addEventListener('change', function(event) {
            alert('You selected option: ' + event.target.value);
        });
    </script>
</body>

</html>

焦点事件监听器

此示例演示如何使用事件监听器来响应输入字段上的焦点和失焦事件,基于用户与网页的交互。

 
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Focus Event Listener</title>
</head>

<body>
  <h2 align = "center">HTML - DOM Element </h2>
  <h3 align = "center">addEventListener() Method
  <br><br>Focus Event
  </h3>
  <label for="nameInput">Enter your name:</label>
  <input type="text" id="nameInput">
  <div id="message"></div>

  <script>
    document.addEventListener
    ('DOMContentLoaded', function() {
      let nameInput = document.getElementById
      ('nameInput');
      let messageBox = document.getElementById
      ('message');

      nameInput.addEventListener('focus', function() {
        messageBox.textContent = 'Input field focused.';
        messageBox.style.color = 'green';
      });

      nameInput.addEventListener('blur', function() {
        messageBox.textContent = 'Input field blurred.';
        messageBox.style.color = 'black';
      });
    });
  </script>
</body>

</html>    

动态处理输入长度限制

此示例向输入字段添加按键事件监听器,该监听器验证输入长度,如果超过最大长度则显示消息。

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Handling input length Event Listener
  </title>
</head>

<body>
  <h2 align = "center">HTML - DOM Element </h2>
  <h3 align = "center">addEventListener() Method
  <br><br>Handling Input Length Event
  </h3>
  <label for="textInput">
  Enter Text (max 10 characters):
  </label>
  <input type="text" id="textInput">
  <div id="message"></div>

  <script>
    document.addEventListener
    ('DOMContentLoaded', function() {
      let textInput=document.getElementById('textInput');
      let messageBox =document.getElementById('message');

      textInput.addEventListener
      ('keypress', function(event) {
        if (textInput.value.length >= 10) {
            // Prevent further keypresses  
          event.preventDefault(); 
          messageBox.textContent = 
          'Maximum length reached.';
        } else {
          messageBox.textContent = '';
        }
      });
    });
  </script>
</body>

</html>

处理滚动事件

此示例向窗口添加滚动事件监听器,在用户向下滚动页面时显示消息。

<!DOCTYPE html>
<html lang="en">
<head> 
    <style>
    body {
        height: 1500px;  
    }
    #messageBox {
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background-color: #f0f0f0;
        padding: 10px;
        border: 1px solid #ccc;
        display: none;
    }
    </style>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">addEventListener() Method
    <br><br>Scroll Event
    </h3>
    <p>Scroll down.........</p>

    <div id="messageBox">You scrolled down!</div>
    <script>
    document.addEventListener
    ('DOMContentLoaded', function() {
        let messageBox = document.getElementById
        ('messageBox');

        window.addEventListener('scroll', function() {
        if (window.scrollY > 100) { 
        // Show message after scrolling 100px down
            messageBox.style.display = 'block';
        } else {
            messageBox.style.display = 'none';
        }
        });
    });
    </script>
</body>

</html>    

支持的浏览器

方法 Chrome Edge Firefox Safari Opera
addEventListener() 是 5.0 是 10.0 是 16.0 是 5.1 是 10.6
html_dom_element_reference.htm
广告