阻止事件对象默认行为

Tutorial: DOM操作 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
<!DOCTYPE html>
<html lang="en">
  <head>
    <style></style>
  </head>

  <body>
    <div>123</div>

    <a href="http://www.baidu.com">百度</a>

    <form action="http://www.baidu.com">
      <input type="submit" value="提交" name="sub" />
    </form>

    <script>
      // 常见事件对象的属性和方法
      var div = document.querySelector("div");
      div.addEventListener("click", fn);
      div.addEventListener("mouseover", fn);
      div.addEventListener("mouseout", fn);

      // 1. 返回事件类型
      function fn(e) {
        console.log(e.type); // click | mouseover | mouseout
      }

      // 2. 阻止默认行为(事件) 让链接不跳转 或者让提交按钮不提交
      var a = document.querySelector("a");
      // a.addEventListener("click", function (e) {
      //   e.preventDefault(); //  dom 标准写法
      // });

      // 3. 传统的注册方式
      a.onclick = function (e) {
        // 普通浏览器 e.preventDefault();  方法
        // e.preventDefault();
        // 低版本浏览器 ie678  returnValue  属性
        // e.returnValue;
        // 我们可以利用return false 也能阻止默认行为 没有兼容性问题 特点: return 后面的代码不执行了, 
        // 而且只限于传统的注册方式
        return false;
        alert(11);
      };

      // 组织表单提交
      var form = document.querySelector("form");
      form.onsubmit = function (e) {
        e.preventDefault();
        console.log(e);
      };
    </script>
  </body>
</html>