jQuery事件

1、jQuery封装的事件

jQuery对JS的事件进行了封装,编写JS程序时不必再考虑浏览器的兼容性。jQuery库封装了JS常用事件,以方便开发者很便捷地绑定这些事件。jQuery封装的常用事件如下表所示:

2、事件绑定

第一种:使用bind()函数

bind(事件类型,事件处理)

        $("div").bind("click",function(){
            $(this).css("color","pink");
        })

第二种:使用 on 进行数据绑定

on 进行绑定事件时可以实现动态绑定

        $("div").on({
            "click": function () {
                $(this).css("color", "pink");
            },
            "mouseover": function () {
                $(this).css("background-color", "yellow");
            },
            "mouseout": function () {
                $(this).css("background-color", "red");
            }
        })

 第三种:实现body标签中的所有div能够绑定上click事件

        $("body").on("click","div",function(){
            $(this).css("color","blue")
        })

3、键盘事件

例:点击A、B、C、D,对div进行颜色切换,点击下向下移动,点击左向左移动

注:记得更换自己的jQuery文件

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            font-size: 20px;
            background-color: red;
            position: relative;
            left: 0;
            top: 0;
        }
    </style>
    <script src="./jquery-3.6.0.min.js"></script>
</head>

<body>
    <div>爱上对方过后就哭了</div>
    <script>
        $(function () {
            var x = 0;
            $(document).on("keydown", function (event) {
                switch (event.keyCode) {
                    case 65:
                        $("div").css("background-color", "green")
                        break;
                    case 66:
                        $("div").css("background-color", "yellow")
                        break;
                    case 67:
                        $("div").css("background-color", "pink")
                        break;
                    case 68:
                        $("div").css("background-color", "aqua")
                        break;
                    case 39:
                        // 一定要在css里写定位
                        x += 10;
                        $("div").css("left", x+"px")
                        break;
                    case 40:
                    x += 10;
                        $("div").css("top", x+"px")
                        break;
                    default:
                        break;
                }
            })
        })
    </script>
</body>

</html>

 

 

 

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值