jQuery事件使用方法总结

jQuery提供了许多的事件处理函数,学习前端一段时间了,下面对其总结一下,梳理一下知识点。

一、鼠标事件 1. click():鼠标单击事件 $div = $("div") $div.click(data,function (event) { //点击盒子变蓝 $(this).css({ "background": "blue", }); console.log(event); })

参数function:匿名函数有且只有一个默认的参数event,event输出事件相关的信息;不允许有其他的参数,可以不写

参数data:有时候需要传递额外的数据给函数,data可以是一个数组,不需要可以省略

扩展:

//event参数可以获取事件的各种属性,有几个常用 event.target: 获取触发事件的元素 $div.click(function (event) { $(event.target).css({ "background": "blue", }); }) event.data: 获取事件传入的参数数据。 event.pageX: 获取鼠标光标点击距离文档左边left的距离; event.pageY: 获取鼠标光标点击距离文档上边top的距离; event.offsetX: 获取鼠标光标点击距离元素左边left的距离; event.offssetY: 获取鼠标光标点击距离元素上边top的距离; event.screenX: 获取鼠标光标点击距离屏幕left的距离; event.screenY: 获取鼠标光标点击距离屏幕top的距离; 2. dblclick():鼠标双击事件 $div = $("div") $div.dblclick()(function (event) { //双击盒子变蓝 $(this).css({ "background": "blue", }); })

参数和click的用法完全一样,event同样可以获取众多的属性。

3. 鼠标进入和离开(进入子元素也触发)

mouseover():进入

mouseout():离开

$div = $("div") $div.mouseover(function (event) { $(this).css({ "background": "blue", }); }) $div.mouseout(function (event) { $(this).css({ "background": "blue", }); })

参数同上,绑定后鼠标进入元素的子元素会再次触发。

4. 鼠标进入和离开(进入子元素不触发)

mouseenter() 鼠标进入

mouseleave() 鼠标离开

$div = $("div") $div.mouseenter(function (event) { $(this).css({ "background": "blue", }); }) $div.mouseleave(function (event) { $(this).css({ "background": "blue", }); })

参数同上,绑定后鼠标进入和离开子元素不会再次触发。

5. hover():同时为mouseenter和mouseleave事件指定处理函数 $div = $("div") // 鼠标进入和移出事件 $div.hover(function (event) { $div.css({ "background": "blue", }) },function (event) { $div.css({ "background": "red", }); })

hover可以同时加入两个function,第一个是鼠标进入触发,第二个是移出触发。

前面不可以添加data参数,否则报错。

6. 鼠标按下和松开

mouseup() 松开鼠标

mousedown() 按下鼠标

$div = $("div") $div.mousedown(function (event) { $(this).css({ "background": "blue", }); console.log(event); }) $div.mouseup(function (event) { $(this).css({ "background": "blue", }); console.log(event); })

参数同click,和点击事件click不同的是,click在鼠标点击(包括按下和松开)后才触发事件,这里是按下或松开就会触发。

7. mousemove() 鼠标在元素内部移动

同法和参数同上。

二、键盘事件 *keypress():按下键盘(指的是按下) $(window).keypress([20],function (event) { $div.css({ "background": "blue", }); console.log(event.which); })

参数:同鼠标事件,第一个参数传递数据,function默认参数event值按下键盘事件。

键盘事件需要绑定可获得焦点的元素,如:input,body,html,一般绑定窗口:window。

如果需要具体判断按下了那个按键,使用event.which,返回键盘字母的ascii码。

注意:如果按下不放开,事件会连续触发。

*按下和松开

keydown() 按下键盘

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/42608c05fa57ab6b83a9c7d03a7fa0c3.html