文章目录
- 一、jQuery
- (一)jQuery简介
- 1.什么是jQuery
- 2.为何要用jQuery
- 3.jQuery版本
- 4.jQuery相关网站
- (二) Jquery基本使用
- 1.引入
- 2.jQuery对象
- 3.文档就绪事件
- 4.链式操作
- 5.jQueryDom和jsDom
- (三)选择器
- (四)筛选器
- (五)标签操作
- 1.标签操作之样式操作
- 2.标签操作之文本内容操作
- 3.标签操作之属性操作
- 4.标签操作之文档处理
- (六)事件
- **1.什么是事件?**
- **2.什么是事件流?**
- **3.总结事件捕获与事件冒泡**
- (七)事件操作
- **1.常见事件**
- **2.事件绑定与解除绑定的方法**
- **3.事件对象**
- **4.绑定事件示例**
- **5.事件冒泡的应用之事件委托**
- **6.练习题**
- (八)动画效果
- (九)补充
- **1、.each()**
- **2、.data()**
一、jQuery
(一)jQuery简介
1.什么是jQuery
1
2
3#1. jQuery 是一个高效、精简并且功能丰富的JavaScript工具库 #2. jQuery极大的简化了JavaScript编程
2.为何要用jQuery
1
2
3
4
5
6
7
8
9
10jQuery的优势(jQuery的宗旨就是:“Write less, do more.“) #1、开源 免费 #2、一款轻量级的JS框架。jQuery核心js文件才几十kb,不会影响页面加载速度。 #3、便捷的选择器与DOM操作, #4、链式表达式。jQuery的链式操作可以把多个操作写在一行代码里,更加简洁。 #5、事件、样式、动画支持。jQuery还简化了js操作css的代码,并且代码的可读性也比js要强。 #6、Ajax操作支持。jQuery简化了AJAX操作,后端只需返回一个JSON格式的字符串就能完成与前端的通信。 #7、跨浏览器兼容。jQuery基本兼容了现在主流的浏览器,不用再为浏览器的兼容问题而伤透脑筋。 #8、插件扩展开发。jQuery有着丰富的第三方的插件,例如:树形菜单、日期控件、图片切换插件、弹出窗口等等基本前端页面上的组件都有对应插件,并且用jQuery插件做出来的效果很炫,并且可以根据自己需要去改写和封装插件,简单实用。
3.jQuery版本
1
2
3
4
5
6
7
8#1.x:兼容IE678,使用最为广泛的,官方只做BUG维护,功能不再新增。因此一般项目来说,使用1.x版本就可以了,最终版本:1.12.4 (2016年5月20日) #2.x:不兼容IE678,很少有人使用,官方只做BUG维护,功能不再新增。如果不考虑兼容低版本的浏览器可以使用2.x,最终版本:2.2.4 (2016年5月20日) #3.x:不兼容IE678,只支持最新的浏览器。需要注意的是很多老的jQuery插件不支持3.x版。目前该版本是官方主要更新维护的版本。 #ps:维护IE678是一件让人头疼的事情,一般我们都会额外加载一个CSS和JS单独处理。值得庆幸的是使用这些浏览器的人也逐步减少,PC端用户已经逐步被移动端用户所取代,如果没有特殊要求的话,一般都会选择放弃对678的支持。
4.jQuery相关网站
- 官网 https://jquery.com/
- 文档API: http://jquery.cuishifeng.cn/index.html
(二) Jquery基本使用
1.引入
先下载到本地,然后引用,才能使用
下载地址:https://jquery.com/download/
1
2
3
4
5
6
7
8
9
10
11
12#方式一:本地引入 <script src="jquery-3.3.1.min.js"></script> <script> //注意,一定在引入jQuery之后,再使用jQuery提供的各种操作 </script> #方式二:直接使用CDN <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> code... </script>
BootCDN jQuery各个版本地址: https://www.bootcdn.cn/jquery/
2.jQuery对象
$
是jQuery
的别名
1
2
3
4jQuery('.item').show() //等同于 $('.item').show()
$
对象可以用作选择器获取元素,还可以创建DOM对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31<!-- 示例:--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: red; /*display: none;*/ } </style> </head> <body> <div class="box"></div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> // jQuery(".box").show() // jQuery(".box").hide() // $(".box").hide() </script> </body> </html>
3.文档就绪事件
(1)DOM文档加载的步骤
- 解析HTML结构。
- 加载外部脚本和样式表文件。
- 解析并执行脚本代码。
- DOM树构建完成。
- 加载图片等外部文件。
- 页面加载完毕。
(2)等待文档加载完毕后执行函数,有两种方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#1、执行时间不同 window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行。 $(document).ready()是DOM结构绘制完毕后就执行,不必等到加载完毕。 #2、编写个数不同 window.onload不能同时编写多个,如果有多个window.onload方法,只会执行一个 $(document).ready()可以同时编写多个,并且都可以得到执行 #3、简化写法不同 window.onload没有简化写法 $(document).ready(function(){})可以简写成$(function(){});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64<!-- 示例: --> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: red; /*display: none;*/ } </style> <script> // 示例1:找不到box // var oDiv=document.getElementsByClassName("box") // alert(oDiv.length) // 0 // 示例2:可以找到box // window.οnlοad=function () { // var oDiv=document.getElementsByClassName("box") // alert(oDiv.length) // 1 // } // 示例3:多个window.onload只会执行一个 // window.οnlοad=function () { // alert(123) // } // window.οnlοad=function () { // alert(456) // } </script> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> // 示例1:可以找到box // $(function () { // var oDiv=document.getElementsByClassName("box") // alert(oDiv.length) // }) // 示例2:可以编写多个 $(function () { alert(123) }) $(function () { alert(456) }) </script> </head> <body> <div class="box"></div> </body> </html>
4.链式操作
1
2
3# 链式调用,原理就是:调用一个实例化方法返回的是当前的对象 $('.box1').css('color','red').next().css('width','200px').css('height','200px').css('background','green').removeAttr('class')
5.jQueryDom和jsDom
1
2
3
4
5
6
7
8
9
10#1、通过原生js获取的dom对象,我们称之为jsDOM或者原生DOM #2、通过jQuery选择器获取的dom对象,我们称之为 jQuery DOM #3、jQuery DOM本质上 是由 jsDOM组成的集合,是个类数组对象。可以通过 [索引] 获取其中的jsDOM,$(jsDOM) 可以转为 jQuery DOM如下 var box = document.getElementsByClassName('box'); #获取js DOM对象 Js DOM对象 ==> JQ DOM对象$(js DOM对象) # 例如 $(box) JQ DOM对象 ==> JS DOM对象 $("选择器")[0] # 或者$("选择器").get(0)
(三)选择器
1.id选择器:
1
2$("#id")
2.标签选择器:
1
2$("tagName")
3.class选择器:
1
2$(".className")
4.所有元素选择器:
1
2$("*")
5.交集选择器:
1
2$("div.c1") // 找到类为c1的div标签
6.并集选择器:
1
2$("#id, .className, tagName")
7.层级选择器:
x和y可以为任意选择器
1
2
3
4
5$("x y"); // x的所有后代y(子子孙孙) $("x > y"); // x的所有儿子y(儿子) $("x + y") // 找到所有紧挨在x后面的y $("x ~ y") // x之后所有的兄弟y
8.基本筛选器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16:first // 第一个 :last // 最后一个 :eq(index)// 索引等于index的那个元素 :even // 匹配所有索引值为偶数的元素,从 0 开始计数 :odd // 匹配所有索引值为奇数的元素,从 0 开始计数 :gt(index)// 匹配所有大于给定索引值的元素 :lt(index)// 匹配所有小于给定索引值的元素 :not(选择器)// 过滤掉所有满足not条件的标签 :has(选择器)// 过滤出所有后代中满足has条件的标签 #例如 $("div:has(h1)")// 找到所有后代中有h1标签的div标签 $("div:has(.c1)")// 找到所有后代中有c1样式类的div标签 $("li:not(.c1)")// 找到所有不包含c1样式类的li标签 $("li:not(:has(a))")// 找到所有!!!后代中!!!不含a标签的li标签
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80<!-- JQ版自定义模态框 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQ版模态框</title> <style> * { margin:0; padding: 0; } html,body { height: 100%; } #bg { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background-color: rgba(0,0,0,0.3); display: none; } #content { position: absolute; top: 100px; left: 50%; margin-left: -150px; background-color: white; width: 300px; height:200px; } #content p:nth-child(3) { position: absolute; top: 100px; } </style> </head> <body> <input type="button" value="弹出" id="btn"> <div id="bg"> <div id="content"> <p> <label for="inp-username">用户名:</label><input type="text" name="username" id="inp-username"> </p> <p> <label for="inp-password">密码:</label><input type="text" name="password" id="inp-password"> </p> <p> <input type="button" value="提交"> <input type="button" value="取消" id="cancel"> </p> </div> </div> <script src="jquery.min.js"></script> <script> // // 混合使用版 // $("#btn")[0].οnclick=function () { // $("#bg").css('display','block') // } // $("#cancel")[0].οnclick=function () { // $("#inp-username").val("") // $("#inp-password").val("") // $("#bg").css('display','none') // } // JQ版 $("#btn").click(function () { $("#bg").css('display','block') }) $("#cancel").click(function () { $("#inp-username").val("") $("#inp-password").val("") $("#bg").css('display','none') }) </script> </body> </html>
9.属性选择器:
1
2
3
4[attribute] [attribute=value]// 属性等于 [attribute!=value]// 属性不等于
例子:
1
2
3
4
5
6
7// 示例 <input type="text"> <input type="password"> <input type="checkbox"> $("input[type='checkbox']");// 取到checkbox类型的input标签 $("input[type!='text']");// 取到类型不是text的input标签
10.表单
(1)常用筛选:
1
2
3
4
5
6
7
8
9:text // input控件中,type属性明文显示 :password // input控件中,type属性密文显示 :file // input控件中,type属性上传文件 :radio // input控件中,type属性单选框 :checkbox // input控件中,type属性复选框 :submit // input控件中,type属性提交按钮 :reset // input控件中,type属性重置按钮 :button // input控件中,type属性普通按钮
例子:
1
2$(":checkbox") // 找到所有的checkbox
(2)表单对象属性:
1
2
3
4
5:enabled // input控件中,不禁用控件,可提交数据 :disabled // input控件中,禁用控件,不可提交数据 :checked // input控件中选择框,用于设置默认值 :selected // select控件中,用于设置默认值
例子:
找到可用的input标签
1
2
3
4
5
6
7<form> <input name="email" disabled="disabled" /> <input name="id" /> </form> $("input:enabled") // 找到可用的input标签
找到被选中的option:
1
2
3
4
5
6
7
8
9<select id="s1"> <option value="beijing">北京市</option> <option value="shanghai">上海市</option> <option selected value="guangzhou">广州市</option> <option value="shenzhen">深圳市</option> </select> $(":selected") // 找到所有被选中的option
(四)筛选器
下一个兄弟元素:
1
2
3
4$("#id").next() // 后一个兄弟 $("#id").nextAll() // 后面所有兄弟 $("#id").nextUntil("#i2") // 与“i2”之间的后面所有兄弟
上一个兄弟元素:
1
2
3
4$("#id").prev() // 前一个兄弟 $("#id").prevAll() // 前面所有兄弟 $("#id").prevUntil("#i2") // 前面所有兄弟,与“i2”之间的
父亲元素:
1
2
3
4$("#id").parent() $("#id").parents() // 查找当前元素的所有的父辈元素 $("#id").parentsUntil() // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。
儿子和兄弟元素:
1
2
3$("#id").children();// 儿子们 $("#id").siblings();// 兄弟们
查找
搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。
1
2$("div").find("p")
等价于$(“div p”)
筛选
筛选出与指定表达式匹配的元素集合。这个方法用于缩小匹配的范围。用逗号分隔多个表达式。
1
2$("div").filter(".c1") // 从结果集中过滤出有c1样式类的
等价于 $(“div.c1”)
补充:
1
2
3
4
5
6.first() // 获取匹配的第一个元素 .last() // 获取匹配的最后一个元素 .not() // 从匹配元素的集合中删除与指定表达式匹配的元素 .has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。 .eq() // 索引值等于指定值的元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88<!-- 左侧菜单示例 --> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } html { height: 100%; } body { height: 100%; } .left { width: 20%; height: 100%; background-color: #30353c; } .title { /*width: 100%;*/ text-align: center; height: 50px; line-height: 50px; color: white; border-bottom: 1px solid #000; } .item { text-align: center; height: 30px; line-height: 30px; color: white; border-bottom: 1px solid #31353b; background-color: #191c20; } .hide { display: none; } </style> </head> <body> <div class="left"> <div class="menu"> <div class="title">菜单一</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> <div class="title">菜单二</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> <div class="title">菜单三</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> </div> </div> <script src="jquery-3.3.1.min.js"></script> <script> $('.title').click(function () { // jQuery绑定事件 // 隐藏所有class里有.items的标签 $('.items').addClass('hide'); //批量操作 $(this).next().removeClass('hide'); }) </script> </body> </html>
(五)标签操作
1.标签操作之样式操作
(1)样式类
1
2
3
4
5addClass(); // 添加指定的CSS类名。 removeClass(); // 移除指定的CSS类名。 hasClass(); // 判断样式存不存在 toggleClass(); // 切换CSS类名,如果有就移除,如果没有就添加。
CSS
1
2css("color","red") //DOM操作:tag.style.color="red"
示例:
1
2$("p").css("color", "red"); //将所有p标签的字体设置为红色
(2)位置:
1
2
3
4
5
6
7
8
9
10offset() // 获取匹配元素在当前窗口的相对偏移或设置元素位置 position() // 获取匹配元素相对父元素的偏移 scrollTop() // 获取匹配元素相对滚动条顶部的偏移 scrollLeft() // 获取匹配元素相对滚动条左侧的偏移 例1 $("#bb").offset({"left":100,"top":100}) 例2 $(window).scrollTop(0); // 跳到首页
.offset()
方法允许我们检索一个元素相对于文档(document)的当前位置。
和 .position()
的差别在于: .position()
是相对于相对于父级元素的位移。
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66<!-- 返回顶部示例 --> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> img { width: 500px; } #button1 { width: 100px; height: 50px; background-color: #b9950c; } .box1 { width: 200px; height: 20000px; border: 1px solid #000; } .button2 { width: 50px; height: 50px; background-color: #3a6696; position: fixed; right: 15px; bottom: 15px; } .hide { display: none; } </style> </head> <body> <input type="button" value="妹子走你" id="button1"> <div class="box2"> <img src="http://p2.cri.cn/M00/06/0A/CqgNOlmMbN2AEhkXAAAAAAAAAAA136.2562x1736.jpg" alt=""> </div> <div class="box1">1</div> <button id="button2" class="button2 hide">回到顶部</button> <script src="jquery-3.3.1.min.js"></script> <script> $('#button1').click(function () { $('.box2').offset({left: 300, top: 100}); }); $(window).scroll(function () { if ($(window).scrollTop() > 100) { $('#button2').removeClass('hide'); } else { $('#button2').addClass('hide'); } }); $('#button2').click(function () { $(window).scrollTop(0); }); </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78<!-- 匀速移动到顶部 --> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> img { width: 500px; } #button1 { width: 100px; height: 50px; background-color: #b9950c; } .box1 { width: 200px; height: 20000px; border: 1px solid #000; } .button2 { width: 50px; height: 50px; background-color: #3a6696; position: fixed; right: 15px; bottom: 15px; } .hide { display: none; } </style> </head> <body> <input type="button" value="妹子走你" id="button1"> <div class="box2"> <img src="http://p2.cri.cn/M00/06/0A/CqgNOlmMbN2AEhkXAAAAAAAAAAA136.2562x1736.jpg" alt=""> </div> <div class="box1">1</div> <button id="button2" class="button2 hide">回到顶部</button> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $('#button1').click(function () { $('.box2').offset({left: 300, top: 100}); }); $(window).scroll(function () { if ($(window).scrollTop() > 100) { $('#button2').removeClass('hide'); } else { $('#button2').addClass('hide'); } }); $('#button2').click(function () { var x=$(window).scrollTop() var t=setInterval(function () { x-=10 $(window).scrollTop(x); // 一定要把这一段代码加到这里,加到外面的话,就运行一次就结束了,不会持续判断x的值 if (x <=0){ console.log("ok") $(window).scrollTop(0); clearInterval(t) } },10) }); </script> </body> </html>
(3)尺寸:
1
2
3
4
5
6
7height() width() innerHeight() innerWidth() outerHeight() outerWidth()
2.标签操作之文本内容操作
(1)html
1
2
3
4
5
6
7
8
9
10html()是获取选中标签元素中所有的内容 html(val)设置值:设置该元素的所有内容 会替换掉 标签中原来的内容 $('ul').html('<a href="#">百度一下</a>') //可以使用函数来设置所有匹配元素的内容 $('ul').html(function(){ return '哈哈哈' })
(2)text
1
2
3
4
5
6text() 获取所有匹配元素包含的文本内容 text(val) 设置该所有匹配元素的文本内容 注意:值为标签的时候 不会被渲染为标签元素 只会被当做值渲染到浏览器中
(3)val
1
2
3
4
5
6
7
8
9
10
11
12
13
14// 用途:val()用于操作input的value值 // 示范一: <input type="radio" name="sex" value="male"> <input type="radio" name="sex" value="female"> <input type="radio" name="sex" value="none"> $('input[type=radio]').val(['male',]) // 示范二: <input type="checkbox" name="hobbies" value="111"> <input type="checkbox" name="hobbies" value="222"> <input type="checkbox" name="hobbies" value="333"> $('input[type=checkbox]').val(['111','222'])
3.标签操作之属性操作
(1)用于ID等或自定义属性:
1
2
3
4
5attr(attrName) // 返回第一个匹配元素的属性值 $('.box2 img').attr('title','美女') // 为所有匹配元素设置一个属性值 attr({'title': '美女', 'alt':'图片被狗吃了'}) // 为所有匹配元素设置多个属性值 removeAttr('title') // 从每一个匹配的元素中删除一个属性
(2)用于checkbox和radio
1
2
3
4prop('value') // 获取value属性的值 prop('checked',true); // 设置属性 removeProp('value') // 移除value属性
注意:
在1.x及2.x版本的jQuery中使用attr对checkbox进行赋值操作时会出bug,在3.x版本的jQuery中则没有这个问题。为了兼容性,我们在处理checkbox和radio的时候尽量使用特定的prop(),不要使用attr(“checked”, “checked”)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<h3>爱好</h3> <input type="checkbox" name="hobbies" value="basketball">篮球 <input type="checkbox" name="hobbies" value="football">足球 <input type="checkbox" name="hobbies" value="coding">编程 <h3>性别</h3> <input type="radio" name="sex" value="male"> <input type="radio" name="sex" value="female"> <input type="radio" name="sex" value="none"> <script> $(':checkbox[value=football]').prop('checked',true); $(':radio[value=male]').prop('checked',true); </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60<!-- 示例:全选、反选、取消 --> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h3>菜单</h3> <input type="button" value="全选" id="all"> <input type="button" value="反选" id="reverse"> <input type="button" value="取消" id="cancel"> <p> 蒸羊羔<input type="checkbox" name="menu"> </p> <p> 蒸鹿茸<input type="checkbox" name="menu"> </p> <p> 蒸熊掌<input type="checkbox" name="menu"> </p> <p> 烧花鸭<input type="checkbox" name="menu"> </p> <p> 烧雏鸡<input type="checkbox" name="menu"> </p> <p> 烧子鹅<input type="checkbox" name="menu"> </p> <script src="jquery-3.3.1.min.js"></script> <script> $('#all').click(function () { $('p input').prop('checked', true); }); $('#reverse').click(function () { $('p input').each(function () { $(this).prop('checked', !$(this).prop('checked')); }) }); $('#cancel').click(function () { $('p input').prop('checked', false); }); </script> </body> </html>
4.标签操作之文档处理
1
2
3
4
5
6
7
8//内部 $(A).appendTo(B) // 把A追加到B内部的最后面 $(A).prependTo(B) // 把A前置到B内部的最前面 //外部 $(A).insertAfter(B) // 把A放到B外部的后面 $(A).insertBefore(B) // 把A放到B外部的前面
1
2
3
4
5
6
7
8//内部 $(A).append(B) // 把B追加到A内部的最后 $(A).prepend(B) // 把B前置到A内部的最前面 //外部 $(A).after(B) // 把B放到A外部的后面 $(A).before(B) // 把B放到A外部的前面
移除和清空元素
1
2
3$('.p1').remove() // 从DOM中删除所有匹配的元素。====>把元素本身删掉 $('.p1').empty() // 删除匹配的元素集合中所有的子节点====》把元素的子元素都删掉(包含文本内容)
练习题:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167<!--表格内容增删改--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } .cover { position: absolute; left: 0; right: 0; top: 0; bottom: 0; background-color: rgba(150, 150, 150, 0.3); } .modal { position: absolute; width: 500px; height: 300px; left: 50%; top: 200px; margin-left: -250px; background-color: white; } .hide { display: none; } </style> </head> <body> <input type="button" value="新增" id="add"> <table border="1px" cellspacing="0px"> <thead> <tr> <th>#</th> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Egon</td> <td>18</td> <td> <input type="button" value="编辑" class="edit"> <input type="button" value="删除" class="del"> </td> </tr> </tbody> </table> <div class="cover hide"></div> <div class="modal hide"> <label for="name">姓名</label><input type="text" id="name"> <label for="age">年龄</label><input type="text" id="age"> <input type="button" value="提交" id="submit"> <input type="button" value="取消" id="cancel"> </div> <script src="jquery-3.3.1.min.js"></script> <script> // 显示模态框 function show() { $('.cover').removeClass('hide'); $('.modal').removeClass('hide'); } // 隐藏模态框 function hide() { $('.cover').addClass('hide'); $('.modal').addClass('hide'); } // 清除输入框内容 function clear() { $('#name,#age').val(''); } let current_obj=''; function bind() { // 点击编辑按钮,修改全局变量submit_tag='edit',提交时则执行编辑内容的功能; $('.edit').click(function () { submit_tag = 'edit'; current_obj=this; show(); let name=$(this).parent().siblings()[1].innerHTML; let age=$(this).parent().siblings()[2].innerHTML; $('#name').val(name); $('#age').val(age); }); $('.del').click(function () { let tdList = $(this).parent().parent().nextAll(); for (let i = 0; i < tdList.length; i++) { let num = $(tdList[i]).children()[0].innerHTML; $(tdList[i]).children()[0].innerHTML = num - 1; } $(this).parent().parent().remove(); }); } // 为现有的编辑和删除按钮绑定事件 bind(); let submit_tag = ''; // 点击新增按钮,修改全局变量submit_tag='add',提交时则执行添加新内容的功能; $('#add').click(function () { submit_tag = 'add'; show(); }); // 点击提交按钮,根据全局变量submit_tag的值,来执行不同的功能; $('#submit').click(function () { if (submit_tag == 'add') { //添加新内容的功能 let tr = document.createElement('tr'); let td1 = document.createElement('td'); let td2 = document.createElement('td'); let td3 = document.createElement('td'); let td4 = document.createElement('td'); td1.innerHTML = $('tbody tr').length + 1; td2.innerHTML = $('#name').val(); td3.innerHTML = $('#age').val(); td4.innerHTML = '<input type="button" value="编辑" class="edit">n' + '<input type="button" value="删除" class="del">'; $(td1).appendTo(tr); $(td2).appendTo(tr); $(td3).appendTo(tr); $(td4).appendTo(tr); $(tr).appendTo($('tbody')); bind(); hide(); clear() } else if (submit_tag == 'edit') { //编辑已经存在内容的功能 let tdL=$(current_obj).parent().siblings(); tdL[1].innerHTML=$('#name').val(); tdL[2].innerHTML=$('#age').val(); hide(); clear(); } }); $('#cancel').click(function () { clear(); hide(); }); </script> </body> </html>
替换
1
2
3replaceWith() replaceAll()
克隆
1
2
3
4clone() // clone方法不加参数true,克隆标签但不克隆标签带的事件 // clone方法加参数true,克隆标签并且克隆标签带的事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41<!--案例:点击复制--> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>克隆</title> <style> #b1 { background-color: deeppink; padding: 5px; color: white; margin: 5px; } #b2 { background-color: dodgerblue; padding: 5px; color: white; margin: 5px; } </style> </head> <body> <button id="b1">屠龙宝刀,点击就送</button> <hr> <button id="b2">屠龙宝刀,点击就送</button> <script src="jquery-3.3.1.min.js"></script> <script> // clone方法不加参数true,克隆标签但不克隆标签带的事件 $("#b1").on("click", function () { $(this).clone().insertAfter(this); }); // clone方法加参数true,克隆标签并且克隆标签带的事件 $("#b2").on("click", function () { $(this).clone(true).insertAfter(this); }); </script> </body> </html>
(六)事件
1.什么是事件?
1
2
3
4
5
6
7
8//什么是事件??? 鼠标点击click、页面滚动onscroll、鼠标悬停mouseover等对元素的操作称之为事件,对HTML元素产生的事件可以被绑定上具体的操作,称之为事件绑定,比如在点击某一个元素时触发某个功能的执行 // 注意: 首先我们要知道,浏览器中的各种操作不是因为我们绑定事件之后才存在,即便是我们不对任何元素绑定任何事件,我们仍然可以对元素进行各种如click、mouseover等等操作 只不过没有为元素绑定事件时,触发click或mouseover等操作将不会执行任何动作 总结下来,我们之所以绑定事件,就是因为想要在触发某个操作时去执行一些动作/函数而非无所事事
2.什么是事件流?
由于html是一个树形嵌套结构,如下
1
2
3
4
5
6
7
8html | |___body | |___div.box1 | |____div.box2
*以点击事件为例,*当我们点击div.box2时,由于div.box2在div.box1里,所以我们同时也在点击div.box1,同理,我们同时也在点击body、同时也在点击html
如果我们为div.box2、div.box1、body、html同时绑定点击事件,那在点击div.box2时,该元素他爹、爷爷、祖爷爷…的点击事件都会触发,具体是谁先触发,按照何种顺序,我们必须了解一下js的事件流
1
2
3
4
5
6
7
8
9
10//事件流描述的是从页面中接收事件的顺序,js事件流分为三个阶段 ① 事件捕获阶段; ② 处于目标阶段; ③ 事件冒泡阶段 // 强调:jQuery只有②③ 阶段以点击事件为例作出比喻:整个屏幕相当于一片草地,点击一下屏幕中的某个位置,相当于在屏幕中埋了一颗地雷事件捕获就是扫雷的过程:从外向里扫雷处于目标阶段就是找到了雷,然后嘣的一声,雷爆炸了事件冒泡阶段就是雷爆炸了向外产生的冲击波:从内向外扩散,以雷为中心方圆几十里地都给丫的炸死
可以通过向文档或者文档中的元素添加“事件侦听器”(addEventListener)来验证上述流程,
addEventListener这个方法接收3个参数:要处理的事件名、事件触发时执行的函数、一个布尔值。
布尔值参数如果是true,表示在捕获阶段执行函数;如果是false,表示在冒泡阶段执行函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62<!--示例:--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件流</title> <script> window.onload = function () { // 1、事件捕获阶段: document.addEventListener('click', function () { // document代表的是整个html页面; console.log('document处于事件捕获阶段'); }, true); document.documentElement.addEventListener('click', function () { // document.documentElement代表的是<html>标签; console.log('html处于事件捕获阶段'); }, true); document.body.addEventListener('click', function () { // document.body代表的是<body>标签; console.log('body处于事件捕获阶段'); }, true); var oBtn = document.getElementById('btn'); oBtn.addEventListener('click', function () { // btn标签 console.log('btn处于事件捕获阶段'); }, true); // 2、处于目标阶段 // 3、事件冒泡阶段 document.addEventListener('click', function () { // document代表的是整个html页面; console.log('document处于事件冒泡阶段'); }, false); document.documentElement.addEventListener('click', function () { // // document.documentElement代表的是<html>标签; console.log('html处于事件冒泡阶段'); }, false); document.body.addEventListener('click', function () { // document.body代表的是<body>标签; console.log('body处于事件冒泡阶段'); }, false); oBtn.addEventListener('click', function () { // btn console.log('btn处于事件冒泡阶段'); }, false); }; </script> </head> <body> <!-- href="javascript:;"代表阻止默认事件 --> <a href="javascript:;" id="btn">按钮</a> </body> </html>
当我们点击这个btn的时候,看看页面都输出了什么:
3.总结事件捕获与事件冒泡
1
2
3// 1、事件捕获指的是从document到触发事件的那个元素:自上而下的去触发事件 // 2、事件冒泡指的是从触发事件的那个元素到document:自下而上的去触发事件
(七)事件操作
1.常见事件
2.事件绑定与解除绑定的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } .box1 { width: 500px; height: 500px; background-color: gray; } </style> </head> <body> <div class="box1"> div1 </div> <script src="jquery-3.3.1.min.js"></script> <script> // 绑定方式一: $('.box1').click(function () { alert('绑定方式一') }); // 绑定方式二: $('.box1').bind('click', function () { alert('绑定方式二') }); $('.box1').bind('mouseover mouseout', function () { // 绑定多个事件做同一件事 console.log('绑定多个事件做同一件事') }); $('.box1').bind({ 'mouseup': function () { console.log('mouseover'); }, 'mousedown': function () { console.log('mouseout'); } }); // 移除事件,unbind没有参数则代表移除所有事件 setTimeout(function () { alert('3s啦。。。mouseover失效'); $('.box1').unbind('mouseover'); }, 3000); setTimeout(function () { alert('10s啦。。。所有事件移除'); $('.box1').unbind(); }, 10000) </script> </body> </html>
3.事件对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } .box1 { width: 500px; height: 500px; background-color: gray; } .box2 { width: 200px; height: 200px; background-color: red; } </style> </head> <body> <div class="box1"> div1 <div class="box2">div2</div> </div> <script src="jquery-3.3.1.min.js"></script> <script> // this和event.target // 相同之处: // 1、this和event.target都是js dom对象 // 不同之处: // 1、js中事件是会冒泡的,所以this是会变化的,但event.target不会变化,它永远是直接接受事件的目标js DOM元素,这一点区别将在后续的事件委托的知识点中体现; $('.box2').bind('click',function (event) { console.log(event.type); // event.type事件的类型为:click console.log(event.target); // event.target指的是点击的那个元素 console.log(event.pageX); // 点击事件/点击位置相对于窗口的X轴位置 console.log(event.pageY); }) // 常用的事件方法:1 阻止事件冒泡 2.阻止默认事件 // ev.preventDefault() 阻止默认事件 // ev.stopPropagation()阻止事件冒泡 // return false 既阻止默认事件又阻止事件冒泡 </script> </body> </html>
4.绑定事件示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } .box1 { width: 800px; height: 800px; background-color: gray; } .box2 { width: 300px; height: 300px; background-color: red; } </style> </head> <body> <div class="box1"> div1 <div class="box2">div2 <input type="text" id="inp"> <br> 男<input type="radio" name="sex" value="male"> 女<input type="radio" name="sex" value="female"> 未解之谜<input type="radio" name="sex" value="none"> <select name="city" id="select"> <option value="bj">北京</option> <option value="sh">上海</option> </select> <br> <input type="text" id="inp1" value="我就是我,一个忧郁的美男子"> <br> <textarea name="" id="inp2" cols="5" rows="5"> 你选中我,我就是触发了 </textarea> <form action="https://www.baidu.com" id="form"> 用户名:<input type="text" name="user"> <br> 密码:<input type="text" name="pwd"> <br> <input type="submit" value="提交" id="submit"> </form> </div> </div> <script src="jquery-3.3.1.min.js"></script> <script> // 鼠标事件 // click与dblclick只应该存在一个,大多数都是单击事件 $('.box1').click(function (event) { // console.log(event.type); // event.type事件的类型为:click console.log(event.target); // event.target指的是点击的那个元素 }) $('.box1').dblclick(function (event) { console.log(event.target); // event.target指的是点击的那个元素 }) $('.box1').mousedown(function (event) { console.log('按照鼠标左键不松手'); }); $('.box1').mouseup(function (event) { console.log('按照鼠标左键松手'); }); $('.box1').mousemove(function (event) { console.log('移动鼠标', event.pageX, event.pageY); }); $('.box1').mouseover(function (event) { console.log('元素以及该元素的子元素在鼠标移入时都会触发,当前的div是:', event.target.innerText); }); $('.box1').mouseout(function (event) { console.log('元素以及该元素的子元素在鼠标离开时都会触发,当前的div是:', event.target.innerText); }); $('.box1').mouseenter(function (event) { console.log('元素以在鼠标移入时都会触发(与子元素无关),当前的div是:', event.target.innerText); }); $('.box1').mouseleave(function (event) { console.log('元素以在鼠标移入时都会触发(与子元素无关),当前的div是:', event.target.innerText); }); $('#inp').focus(function (event) { console.log('鼠标聚焦'); }); $('#inp').blur(function (event) { console.log('鼠标失去焦点'); }); // 往输入框内输入内容时,键盘的任意键按下则触发=》即先触发,再出内容 $('#inp').keydown(function (event) { console.log('键盘按键按下'); }); // 往输入框内输入内容时,键盘的任意键抬起则触发=》即先出内容,再触发 $('#inp').keyup(function (event) { console.log('键盘按键弹起'); }); //表单事件change:当输入框的内容改变,并且失去焦点时,就会触发 $('#inp').change(function () { console.log(this.value); }); $('input[name=sex]').change(function (event) { console.log(this.value); }); $('#select').change(function () { console.log(this.value); }); //表单事件select:当输入框的内容被选中时就触发 $('#inp1').select(function () { console.log(this.value); }); $('#inp2').select(function () { console.log(this.value); }); //表单事件submit $('#form').submit(function (event) { console.log($('input[name=user]').val()); console.log($('input[name=pwd]').val()); event.preventDefault(); }); </script> </body> </html>
5.事件冒泡的应用之事件委托
添加的事件不能用于未来动,例如之前我们在做表格的增删改时,每新增一行内容都需要重新绑定事件,基于事件委托就可以解决该问题
事件委托是通过事件冒泡的原理,利用父标签去捕获子标签的事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } ul { list-style: none; border: 1px solid #000; } .baba { border: 1px solid red; } </style> </head> <body> <div class="baba"> <ul> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> <li>item6</li> </ul> </div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $('ul').on('mouseover','li',function (e) { $(e.target).css('background-color','#ddd').siblings().css('background-color','white'); // e.stopPropagation(); // return false; }) $(".baba").mouseover(function () { alert("你应该在我的儿子里组织事件冒泡!!!") }) </script> </body> </html>
如果不基于事件冒泡,有的人可以想这么做
1
2
3
4$("li").on("mouseover", function () { $(this).css("background-color", "#ddd").siblings().css("background-color", "white"); })
这么做看起来可以达到目标,但存在两方面的问题
1
2
3
4
5//1、比起事件委托,该方式需要遍历所有li节点,性能较低。 //2、如果我们在绑定事件完成后,页面又动态的加载了一些元素…… $("<li>item7</li>").appendTo("ul"); 该方式需要我们给新增的元素再绑定一次事件
6.练习题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129<!--练习1:键盘事件,按shift进行批量操作--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <table border="1"> <thead> <tr> <th>#</th> <th>姓名</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td> <input type="checkbox" name="member"> </td> <td>EGON</td> <td> <select name="state"> <option value="online">上线</option> <option value="downline">下线</option> <option value="out">离职</option> </select> </td> </tr> <tr> <td> <input type="checkbox" name="member"> </td> <td>Lxx</td> <td> <select name="state"> <option value="online">上线</option> <option value="downline">下线</option> <option value="out">离职</option> </select> </td> </tr> <tr> <td> <input type="checkbox" name="member"> </td> <td>Alex</td> <td> <select name="state"> <option value="online">上线</option> <option value="downline">下线</option> <option value="out">离职</option> </select> </td> </tr> <tr> <td> <input type="checkbox" name="member"> </td> <td>Wxx</td> <td> <select name="state"> <option value="online">上线</option> <option value="downline">下线</option> <option value="out">离职</option> </select> </td> </tr> <tr> <td> <input type="checkbox" name="member"> </td> <td>Yxx</td> <td> <select name="state"> <option value="online">上线</option> <option value="downline">下线</option> <option value="out">离职</option> </select> </td> </tr> </tbody> </table> <input type="button" value="全选" id="btn1"> <input type="button" value="反选" id="btn2"> <input type="button" value="取消" id="btn3"> <script src="jquery-3.3.1.min.js"></script> <script> $('#btn1').click(function () { $('input[name=member]').prop('checked',true); }); $('#btn2').click(function () { $('input[name=member]').each(function () { $(this).prop('checked',!$(this).prop('checked')); }); }); $('#btn3').click(function () { $('input[name=member]').prop('checked',false); }); // 按住shift键,批量操作 let tag=false; $(window).keydown(function (event) { if(event.keyCode == 16){ // 如果按下shift键,则开启批量模式 tag=true; } }); $(window).keyup(function (event) { if(event.keyCode == 16){ // 如果松开shift键,则关闭批量模式 tag=true; } }); $('table select').change(function () { if (tag){ // 如果开启了批量模式,则批量修改已经选中的input标签关于操作一栏的状态 $('input:checked').parent().parent().find('select').val($(this).val()); } }); </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82<!--练习2:hover事件--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } .header { height: 50px; background-color: #3d3d3d; } ul li{ list-style: none; width: 70px; height: 50px; line-height: 50px; text-align: center; margin-right: 10px; float: left; font-size: 15px; color: #b0b0b0; } ul li:hover { background-color: #242424; } ul li p { width: 700px; height: 70px; background-color: #242424; overflow: auto; color: #b0b0b0; line-height: 70px; position: absolute; left: 0; } .hide { display: none; } .active .son { display: block; } </style> </head> <body> <div class="header"> <ul> <li> 登录 <p class="hide son">怒髪冲冠,凭栏处、潇潇雨歇</p> </li> <li> 注册 <p class="hide son">抬望眼,仰天长啸,壮怀激烈。</p> </li> <li>购物车 <p class="hide son">三十功名尘与,八千里路云和月。</p> </li> <li> 我的订单 <p class="hide son">莫等闲、白了少年头,空悲切。</p> </li> </ul> </div> <script src="jquery-3.3.1.min.js"></script> <script> $('ul li').hover( function () { $(this).addClass('active'); }, function () { $(this).removeClass('active'); } ); </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28<!--练习3:实时监听input输入值变化--> <!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"> <title>实时监听input输入值变化</title> </head> <body> <input type="text" id="i1"> <script src="jquery-3.3.1.min.js"></script> <script> /* * on input是HTML5的标准事件 * 能够检测textarea,input:text,input:password和input:search这几个元素的内容变化, * 在内容修改后立即被触发,不像on change事件需要失去焦点才触发 * on input事件在IE9以下版本不支持,需要使用IE特有的on propertychange事件替代 * 使用jQuery库的话直接使用on同时绑定这两个事件即可。 * */ $("#i1").on("input propertychange", function () { alert($(this).val()); }) </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60<!--练习4:登录校验示例--> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录注册示例</title> <style> .error { color: red; } </style> </head> <body> <form id="myForm" action="https://www.baidu.com"> <label for="name">姓名</label><input type="text" id="name" name="username"> <span class="error"></span> <label for="passwd">密码</label><input type="password" id="passwd" name="password"> <span class="error"></span> <input type="submit" id="modal-submit" value="登录"> </form> <script src="jquery-3.3.1.min.js"></script> <!--插件:http://www.runoob.com/jquery/jquery-plugin-validate.html--> <script> function myValidation() { // 多次用到的jQuery对象存储到一个变量,避免重复查询文档树 var $myForm = $("#myForm"); $myForm.find(":submit").on("click", function () { // 定义一个标志位,记录表单填写是否正常 var flag = true; $myForm.find(":text, :password").each(function () { if ($(this).val().length <= 0) { var labelName = $(this).prev("label").text(); $(this).next("span").text(labelName + "不能为空"); flag = false; } }); // 表单填写有误就会返回false,阻止submit按钮默认的提交表单事件 return flag; }); // input输入框获取焦点后移除之前的错误提示信息 $myForm.find("input[type!='submit']").on("focus", function () { $(this).next(".error").text(""); }) } // 文档树就绪后执行 $(document).ready(function () { myValidation(); }); </script> </body> </html>
(八)动画效果
1
2
3
4
5
6
7
8
9
10
11
12
13//1、show 概念:显示隐藏的匹配元素 语法:show(speed,callback) 参数: speed:三种预定速度之一的字符串('slow','normal','fast')或表示动画时长的毫秒值(如:1000毫秒==1秒) callback:在动画完成时执行的函数,每个元素执行一次 //2、hide hide(speed,callback)跟show使用方法类似,表示隐藏显示的元素。 可以通过show()和hide()方法,来动态控制元素的显示隐藏 //3、toggle 如果元素是可见的,切换为隐藏的;如果元素是隐藏的,切换为可见的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66<!--示例:--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: #b0b0b0; border: 1px solid #000; display: none; } </style> </head> <body> <div class="box"></div> <input id="btn" type="button" value="显示"> <script src="jquery-3.3.1.min.js"></script> <script> /* var tag = true; $('#btn').click(function () { if (tag) { $('.box').css('display', 'block').text('出来了'); $(this).val('隐藏'); tag = false; } else { $('.box').css('display', 'none').text(''); $(this).val('显示'); tag = true; } }); */ /* var tag = true; $('#btn').click(function () { if (tag) { $('.box').show('slow', function () { $(this).text('出来了'); $('#btn').val('隐藏'); tag = false; }) } else { $('.box').hide(2000, function () { $(this).text(''); $('#btn').val('显示'); tag = true; }); } }); */ $('#btn').click(function () { $('.box').toggle(2000,function () { alert('123'); }); }); </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15//1、slideDown 概念:通过高度变化(向下增大)来到动态地显示所有匹配的元素,在显示完成后触发一个回调函数 用法和参数跟上面类似 //2、slideUp 通过高度变化(向上减小)来动态地隐藏所有匹配的元素,在隐藏完成后可选地触发一个回调函数。 用法和参数跟上面类似 //3、slideToggle 概念:通过高度变化来切换所有匹配元素的可见性,并在切换完成后可选地触发一个回调函数 跟toggle用法类似
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43<!--示例:--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: #b0b0b0; border: 1px solid #000; display: none; } </style> </head> <body> <div class="box"></div> <input id="btn" type="button" value="显示"> <script src="jquery-3.3.1.min.js"></script> <script> /* $(function () { $('#btn').hover(function () { $('.box').slideDown(2000); },function () { $('.box').slideUp(2000); }); }) */ $(function () { $('#btn').hover(function () { $('.box').slideToggle(2000); }); }) </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22//1、fadeIn 概念:通过不透明度的变化来实现所有匹配元素的淡入效果,并在动画完成后可选地触发一个回调函数。 这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化 //2、fadeOut 概念:通过不透明度的变化来实现所有匹配元素的淡出效果,并在动画完成后可选地触发一个回调函数。 这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化。 //3、fadeTo 概念:把所有匹配元素的不透明度以渐进方式调整到指定的不透明度,并在动画完成后可选地触发一个回调函数。 这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化。 //4、fadeToggle 概念:通过不透明度的变化来开关所有匹配元素的淡入和淡出效果,并在动画完成后可选地触发一个回调函数。 这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化。 实现淡入淡出的效果就是使用此方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50<!--示例:--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: red; border: 1px solid #000; } </style> </head> <body> <div class="box"></div> <input type="button" value="显示" id="btn1"> <script src="jquery-3.3.1.min.js"></script> <script> $(function () { /* var tag = true; $('#btn1').mouseover(function () { if (tag) { $('.box').fadeOut(1000); $(this).val('隐藏'); tag = false; } else { // $('.box').fadeIn(1000); $('.box').fadeTo(1000, 0.2); $(this).val('显示'); tag = true; } }); */ $('#btn1').mouseover(function () { $('.box').fadeToggle(1000); }); }) </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29//1、animate 概念:用于创建自定义动画的函数 语法:animate(params,[speed],[fn]) 参数: params:一组包含作为动画属性和终值的样式属性和及其值的集合 speed:三种预定速度之一的字符串("slow","normal", or "fast")或表示动画时长的毫秒数值(如:1000) fn:在动画完成时执行的函数,每个元素执行一次。 //2、stop 概念:停止所有在指定元素上正在运行的动画 语法:stop([clearQueue],[jumpToEnd]) 参数: clearQueue:如果设置成true,则清空队列。可以立即结束动画。 gotoEnd:让当前正在执行的动画立即完成,并且重设show和hide的原始样式,调用回调函数等 //3、delay 概念:用来做延迟的操作 语法:delay(1000),一秒之后做后面的操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58<!--示例:--> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: red; border: 1px solid #000; position: absolute; top: 50px; left: 50px; } </style> </head> <body> <input type="button" value="动起来" id="btn1"> <input type="button" value="停止" id="btn2"> <div class="box">皮卡丘</div> <script src="jquery-3.3.1.min.js"></script> <script> $(function () { /* $('#btn1').click(function () { $('.box').animate( { 'width': '500px', 'height': '500px', 'left': '300px', 'top': '300px' }, 1000 ); }); */ $('#btn1').click(function () { $('.box').animate({'left': '300px'}, 2000).animate({'top': '300px'}, 2000); // $('.box').animate({'left':'500px'},2000).delay(3000).animate({'top':'500px'},2000); }); /*停止、启动动画*/ $('#btn2').click(function () { // .stop() // 停止当前动画 // .stop(true) // 停止所有动画 // .stop(true,true) // 停止所有动画,到达动画终点 $('.box').stop(true); }); }) </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40<!--示例:点赞特效--> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>点赞动画示例</title> <style> div { position: relative; } div > i { color: red; position: absolute; right: 16px; top: -5px; left: 35px; opacity: 1; } </style> </head> <body> <div id="d1">点赞</div> <script src="jquery-3.3.1.min.js"></script> <script> $("#d1").on("click", function () { var newI = document.createElement("i"); newI.innerText = "+1"; $(this).append(newI); $(this).children("i").animate({ opacity: 0 }, 1000) }) </script> </body> </html>
(九)补充
1、.each()
jQuery.each(collection, callback(indexInArray, valueOfElement)):
描述:一个通用的迭代函数,它可以用来无缝迭代对象和数组。数组和类似数组的对象通过一个长度属性(如一个函数的参数对象)来迭代数字索引,从0到length - 1。其他对象通过其属性名进行迭代。
1
2
3
4
5li =[10,20,30,40] $.each(li,function(i, v){ console.log(i, v);//index是索引,ele是每次循环的具体元素。 })
输出:
1
2
3
4
5010 120 230 340
.each(function(index, Element)):
描述:遍历一个jQuery对象,为每个匹配元素执行一个函数。
.each()
方法用来迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。由于回调函数是在当前DOM元素为上下文的语境中触发的,所以关键字 this
总是指向这个元素。
1
2
3
4
5// 为每一个li标签添加foo $("li").each(function(){ $(this).addClass("c1"); });
注意: jQuery的方法返回一个jQuery对象,遍历jQuery集合中的元素 - 被称为隐式迭代的过程。当这种情况发生时,它通常不需要显式地循环的 .each()
方法:
也就是说,上面的例子没有必要使用each()方法,直接像下面这样写就可以了:
1
2$("li").addClass("c1"); // 对所有标签做统一操作
注意:
在遍历过程中可以使用 return false
提前结束each循环。
终止each循环
1
2return false;
2、.data()
.data(key, value): 在匹配的元素上存储任意相关数据/保存一些状态。
1
2$("div").data("k",100);//给所有div标签都保存一个名为k,值为100
**.data(key)????*返回匹配的元素集合中的第一个元素的给定名称的数据存储的值
1
2$("div").data("k");//返回第一个div标签中保存的"k"的值
**.removeData(key)????*移除存放在元素上的数据,不加key参数表示移除所有保存的数据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18$("div").removeData("k"); //移除元素上存放k对应的数据 0px'},2000).delay(3000).animate({'top':'500px'},2000); }); /*停止、启动动画*/ $('#btn2').click(function () { // .stop() // 停止当前动画 // .stop(true) // 停止所有动画 // .stop(true,true) // 停止所有动画,到达动画终点 $('.box').stop(true); }); }) </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40<!--示例:点赞特效--> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>点赞动画示例</title> <style> div { position: relative; } div > i { color: red; position: absolute; right: 16px; top: -5px; left: 35px; opacity: 1; } </style> </head> <body> <div id="d1">点赞</div> <script src="jquery-3.3.1.min.js"></script> <script> $("#d1").on("click", function () { var newI = document.createElement("i"); newI.innerText = "+1"; $(this).append(newI); $(this).children("i").animate({ opacity: 0 }, 1000) }) </script> </body> </html>
最后
以上就是个性老鼠最近收集整理的关于057.jQuery一、jQuery的全部内容,更多相关057内容请搜索靠谱客的其他文章。
发表评论 取消回复