jQuery基础事件

来源:互联网 发布:openjdk7源码下载 编辑:程序博客网 时间:2024/05/16 06:00

学习要点:

  • 绑定事件
  • 简写事件
  • 复合事件

一、绑定事件
bind(type, [data], fn) 的用法
type 表示绑定的事件名称 如click、mouseup等
data 可选,表示传递的额外数据,可以是字符串、数组、对象和数字
fn 事件处理函数

<div id="box">box</div>#box {    height: 100px;    width: 100px;    background: red;}

点击事件—绑定匿名函数

$("#box").bind("click", function() {    alert($(this).text());     // box});

将匿名函数提取出来—传递参数

$("#box").bind("click", "123", fn);function fn(event) {    alert(event.data);      // 123}

同时绑定多个事件

$("#box").bind("mouseover mouseout", function () {    $(this).html(function (index, value) {        return value + "1";         // 之前的值 + "1"    });})

也可以绑定对象

$("#box").bind({    "click" : function () {        console.log("单击");    },    "mouseover" : function () {        console.log("移入");    },    "mouseout" : function () {        console.log("移出");    }});

删除全部的事件

$("#box").unbind();

删除特定的事件—仅仅删除单击事件,对于over out事件依然保留

$("#box").unbind("click");

二、简写事件

第一组:mouseover、mouseout、mouseenter、mouseleave

over、out表示鼠标移入移出触发事件

enter、leave表示鼠标穿过触发事件

区别:enter、leave穿过子元素不会触发事件,而over、out在穿过子元素时会触发事件
当鼠标移入div,strong的innerHTML的值 + “1”;

<div style="width:200px;height:200px;background:green;">    <p style="width:100px;height:100px;background:red;"></p></div><strong></strong>

移入div和p都会触发事件

$("div").mouseover(function() {    $("strong").html(function (index, value) {        return value + "1";    });});

只有移入div才触发事件,移入P不会触发事件

$("div").mouseenter(function () {    $("strong").html(function (index, value) {        return value + "1";    })});

移出div和p都会触发事件

$("div").mouseout(function() {    $("strong").html(function (index, value) {        return value + "1";    });});

只有移出div才触发事件,移出P不会触发事件

$("div").mouseleave(function () {    $("strong").html(function (index, value) {        return value + "1";    })});

第二组:.keydown()、.keyup()返回的是keyCode键码,而.keypress()返回的是charCode字符编码。

<input type="text"/>$("input").keydown(function (e) {    console.log(e.keyCode);});$("input").keypress(function (e) {    console.log(e.charCode);});

第三组:光标激活和丢失
.focus()和.blur()分别表示光标激活和丢失,事件触发时机是当前元素。
.focusin()和.focusout()也表示光标激活和丢失,但事件触发时机可以是子元素。

<div style="width:200px;height:200px;background:red;">    <input type="text" value="" /></div><strong></strong>$("input").focus(function () {     // 当前元素触发    $("strong").html("123");});$("div").focusin(function () {     // 子元素触发    $("strong").html("456");   });

三、复合事件

1.ready(fn) 当 DOM 加载完毕触发事件,不需要等待图片、视频等的加载

$().ready(function () {    alert("234");});

2.hover([fn1,]fn2) 当鼠标移入触发第一个 fn1,移出触发 fn2

<div style="width:200px;height:200px;background:green;">    <p style="width:100px;height:100px;background:red;"></p></div><strong></strong>$("div").hover(function () {    console.log("移入");}, function () {    console.log("移出");});

PS : hover内部封装的是mouseenter和mouseleave,并非mouseover和mouseout,也就是在子元素内移动无效

0 0