Jquery对事件的操作

知识点

  1. 事件绑定
  • $("#btn").bind("click",function(){}):bind绑定事件
  • 简写:$("#btn").click(function(){})
  • unbind("click"):解除事件绑定
  • one("click",function(){}):只执行一次的事件,执行完自动解绑
  1. 合成事件 hover hover(移入函数,移出函数):鼠标移入触发第一个函数,鼠标移出触发第二个函数。
  2. 事件对象e(回调函数参数)
  • e.pageX / e.pageY:鼠标相对于页面的坐标
  • e.target:触发事件的原始DOM元素(事件冒泡起点,和this有区别)
  • e.which:鼠标按键,1左键、2中键、3右键
  • e.altKey / e.shiftKey / e.ctrlKey:布尔值,判断对应功能键是否按下
  • e.keyCode:键盘按键编码

mouseovermouseenter区别:mouseover会事件冒泡,内部子元素也会触发;mouseenter不冒泡。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm31.aspx.cs" Inherits="WebApplication1.WebForm31" %>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
    <style>
        .enter {
            width: 200px;
            height: 100px;
            background-color:blue;
        }

        .leave {
            width: 200px;
            height: 100px;
            background-color:red;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $(document).mousemove(function (e) {
                document.title = e.pageX + "," + e.pageY;
            });

            $("#panel").hover(
                function () {
                    $(this).attr("class","enter");
                },
                function () {
                    $(this).attr("class", "leave");
                })
        });
    </script>
</head>
<body>
    <div style="width: 200px; height: 100px;" id="panel"></div>
</body>
</html>
Code language: HTML, XML (xml)

说明:

  1. 鼠标在页面移动,浏览器标题实时更新为鼠标坐标pageX,pageY
  2. 鼠标移入#panel方块,切换class变为蓝色;移出切换为红色

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注