事件对象属性

jQuery在遵循W3C规范的情况下,对事件对象的常用属性进行了封装,使得事件处理在各大浏览器下都可以正常的运行而不需要进行浏览器类型判断。在jQuery中,有如下常用的事件对象属性。

event.type

该方法的作用是可以获取事件的类型。

<a href="https://www.baidu.com/">百度</a>
<script>
     $("a").click(function(event){
          alert(event.type);    //获取事件类型
          return false;         //阻止链接跳转
     });
</script>

event.preventDefaule()

该方法的作用是阻止默认的事件行为,其特殊之处在于能够兼容所有的浏览器,包括IE,因为在JavaScript中符合W3C规范的preventDefault()方法在IE浏览器中却无效。

<form action="1.html">
  用户名:<input type="text" id="uname" />
  <input type="submit" value="提交" id="sub"/>
</form>
<script>
  $("#sub").click(function(event){
    var uname = $("#uname").val();
    if(uname==""){
      alert("请填写用户名");
      event.preventDefault();
    }
  });
</script>

event.stopPropagation()

 该方法的作用是事件的冒泡。同样,在JavaScript中的stopPropagation()方法在IE浏览器中无效,但是本方法却可以兼容各种浏览器。

<div id="div">
  <span style="color:red;" id="span">我是span</span>
  我是div
</div>
<script>
  $("#span").click(function(event){
    alert($("#span").text());
    event.stopPropagation();
  });
  $("#div").click(function(event){
    alert($("#div").text());
  });
</script>

在上面的代码中,如果不阻止事件冒泡,点击span,会依次出现两个弹框,当在span事件里添加阻止冒泡后,事件只会触发span本身,弹框也只会出现一个。

event.target()

 该方法的作用是获取到触发事件的元素,经过jQuery的封装后,避免了各浏览器不同标准的差异。

<a href="https://www.baidu.com/">百度</a>
<script>
  $("a").click(function(event){
    var tg = event.target;
    alert(tg.href);
    return false;
  })
</script>

event.pageX和event.pageY

这两个方法的作用分别是获取光标相对于页面的x坐标和y左边,在JavaScript中,不同的浏览器对于光标坐标的表示有所差异,在IE中,使用event.x和event.y,在Firefox中使用的是event.pageX和event.pageY,而jQuery对该方法进行了封装,使之能兼容不同的浏览器。

 event.which

该方法的作用是在鼠标单击事件中获取鼠标的左、中、右键(1表示左键,2表示中键,3表示右键),在键盘事件中获取键盘的按键,

<a href="https://www.baidu.com/">百度</a>
<script>
  $("a").click(function(event){
  alert(event.which);
})
</script>

 

event.metaKey

 该方法的作用是获取键盘事件的<ctrl>按键。返回值是Boolean类型,如果按下,则返回true,否则返回false。

原文地址:https://www.cnblogs.com/yuyujuan/p/9445706.html