ZhangYang's Blog

jQuery

jQuery本质和隐式迭代

本质

  • Jquery对象本质“可以看成”是一个包含一个dom数组和所有Jquery方法的容器(方法在所有jq对象共享的jq原型属性prototype中,jq对象本质是一个“类数组”)
  • 每当我们调用选择器方法查找dom树里的元素时,其实就是把找到的dom元素存入一个JQ对象里的dom数组中,然后再把这个JQ对象返回

隐式迭代

  • 当我们调用Jquery方法时(如 html()),jq方法会遍历内部dom数组,并调用每个dom元素的对应的dom属性或方法(如innerHTML),完成操作
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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<input type="button" id="btn" value="按钮">
<script>
$('#btn').click(function(){
//隐式迭代
$('p').text('为了新中国').css('background', 'blue');
});
</script>
</body>
</html>
<!-- 获取元素P,在传统的dom写法中getElementsByTagName发现没有方法名Elements是复数形式
也就是说获得的应该是一个集合设置集合中元素的属性,那必须的迭代啊(遍历)
但是Jquery中不需要遍历可以直接设置,这就是隐式迭代呗 -->

jquery-1.png


jQuery选择器、DOM操作、样式、事件、动画

库和框架的区别

  • 更像是工具,把原生代码功能封装成很多便捷的api,要用的时候再去调用封装的api,需要用到的时候查看文档

框架

  • 更像是一种解决方案,有其自定义的语法,然后用这些语法去填充模板,实现效果。需要用到就了解文档,了解在这个框架下解决问题的模式

jQuery的作用

  • jQuery是一个轻量级的”写得少,做得多(Write less, do more)”的JavaScript库

jQuery库包含以下功能

  • 选择网页元素
  • 改变结果集
  • 元素的操作:取值和赋值
  • 元素的操作:移动
  • 元素的操作:复制、删除和创建
  • 工具方法
  • 事件操作
  • 特殊效果
  • AJAX

jquery对象和原生DOM对象的转化

  • DOM原生对象:通过原生JS获取的对象,使用原生JS的属性和方法
  • jQuery对象:通过jQuery获取的对象,是一个类数组对象,只能使用jQuery自己封装属性和方法
1
2
3
4
5
var name = node.getAttribute('name')
node.setAttribute('name','bar')
var name = $node.attr('name')
$node.attr('name','bar')

jQuery对象转换为DOM原生对象

  • jQuery对象[0]—>DOM原生对象
1
var el = $('div')[0];

DOM原生对象转换为jQuery对象

  • $(DOM原生对象)—>jQuery对象
1
2
var el = document.getElementById('wrap');
var $el = $(el);

jQuery绑定事件

  • jQuery中可以使用bind()/delegate()/live()/on()绑定事件,unbind()和off()对应bind()和on()解除绑定
  • 推荐使用on()事件绑定,off()事件解除绑定,on()提供了绑定事件处理的所有功能,方便快捷

on()绑定事件

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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul class="myUl">
<li>我是1</li>
<li>我是2</li>
<li>我是3</li>
</ul>
<button class="btn">点我增加li</button>
<script>
$('.btn').on('click',function(){
$('.myUl').append('<li>我是4</li>');
})
$('.myUl>li').on('click',function(){
console.log($(this).text());
})
</script>
</body>
</html>

jquery-1.png

  • 上面点击会生成多个’我是li4’,但是无法在生成出来的’我是li4’添加事件,所以点击’我是li4’文本,console.log无反应.要解决这个问题可以用事件代理来解决

on()事件代理

  • 用父级元素来代理监听子集事件的一种方式
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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul class="myUl">
<li>我是1</li>
<li>我是2</li>
<li>我是3</li>
</ul>
<button class="btn">点我增加li</button>
<script>
$('.btn').on('click',function(){
$('.myUl').append('<li>我是4</li>');
})
$('.myUl').on('click','li',function(){
console.log($(this).text());
})
</script>
</body>
</html>

jquery-2.png

off()解除绑定事件

通过传入的第三个参数,仅移除先前绑定的事件处理函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>你好</p>
<script>
var foo = function () {
console.log('我被点击了')
};
$("body").on("click", "p", foo);
// ... foo will no longer be called.
$("body").off("click", "p", foo);
</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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>按钮</button>
<input type="text" value="我是文本">
<script>
var foo = function () {
console.log('我被点击了')
};
$("form").on("click.myClick", "button", foo);
$("form").on("keypress.myClick", "input[type='text']", foo);
$("form").off(".myClick");
</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
<!DOCTYPE html>
<html>
<head>
<style>
button { margin:5px; }
button#theone { color:red; background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="theone">Does nothing...</button>
<button id="bind">Add Click</button>
<button id="unbind">Remove Click</button>
<div style="display:none;">Click!</div>
<script>
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("body").on("click", "#theone", aClick)
.find("#theone").text("Can Click!");
});
$("#unbind").click(function () {
$("body").off("click", "#theone", aClick)
.find("#theone").text("Does nothing...");
});
</script>
</body>
</html>

事件绑定的一些常用操作

向事件处理函数中传入数据,并且在事件处理函数中通过名字来获取传入的数据

1
2
3
4
function myHandler(event) {
console.log(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)

通过使用 .preventDefault(),仅取消默认的动作

1
2
3
$("form").on("submit", function(event) {
event.preventDefault();
});

通过使用 .stopPropagation(),防止提交事件的冒泡行为,但是并不禁止提交行为

1
2
3
$("form").on("submit", function(event) {
event.stopPropagation();
});

其它绑定事件

bind()

  • 给元素绑定一个或多个事件,元素必须存在
1
2
3
$("#btn").bind("click.myClick", function() {
console.log("我被点击了")
})

unbind()

  • 给元素解绑事件
1
$("#btn").unbind("click.myClick")

delegate()

  • 用于事件代理,为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数
1
2
3
4
$("ul").delegate("li", "click.myClick", function() {
var text = $(this).text()
console.log(text)
})

等同于下面on()的写法

1
2
3
4
$("ul").on("click.myClick","li", function() {
var text = $(this).text()
console.log(text)
})

undelegate()

  • 给元素解绑代理事件
1
$("ul").undelegate(".myClick");

live()

  • 这种方法是将页面的document元素作为事件代理元素,太消耗资源,已经过时
  • 推荐使用on方法,因为既能普通绑定事件,也能事件代理绑定

jQuery展示/隐藏元素

改变元素的CSS中的display属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="box">我是文字</div>
<button class="btn-block">显示</button>
<button class="btn-none">隐藏</button>
<script>
$('.btn-block').on('click',function(){
$('.box').css('display','block');
})
$('.btn-none').on('click',function(){
$('.box').css('display','none');
})
</script>
</body>
</html>

用jQuery的show()、hide()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="box">我是文字</div>
<button class="btn-show">显示</button>
<button class="btn-hide">隐藏</button>
<script>
$('.btn-show').on('click',function(){
$('.box').show();
})
$('.btn-hide').on('click',function(){
$('.box').hide();
})
</script>
</body>
</html>

用jQuery的fadeIn()、fadeOut()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="box">我是文字</div>
<button class="btn-fadein">显示</button>
<button class="btn-fadeout">隐藏</button>
<script>
$('.btn-fadein').on('click',function(){
$('.box').fadeIn();
})
$('.btn-fadeout').on('click',function(){
$('.box').fadeOut();
})
</script>
</body>
</html>

jQuery动画

自定义动画

  • jquery使用animate()生成各种动画效果

animate参数说明

  • $(selector).animate(styles,speed,easing,callback);
  • styles: 必需,规定产生动画效果的CSS
  • speed: 可选,规定动画的速度,默认是normal,可能的值:数字(毫秒)、slow、normalfast
  • easing: 可选,规定在不同的动画点中设置动画速度的 easing 函数。内置的 easing 函数: swing linear
  • callback: 可选,animate 函数执行完之后,要执行的函数。
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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="box">你好</div>
<button class="btn">播放动画</button>
<script>
var css = {
width: "70px",
opacity: 0.4,
marginLeft: "60px",
fontSize: "30px"
}
$(".btn").on("click",function(){
$(".box").animate(css, "slow", "linear", function(){
console.log("动画播放完毕")
})
})
</script>
</body>
</html>

停止动画stop()

  • $(selector).stop(stopAll,goToEnd)
  • 可选的 stopAll 参数规定是否应该清除动画队列。默认是 false
  • 可选的 goToEnd 参数规定是否立即完成当前动画。默认是 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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="box">你好</div>
<button class="btn">播放动画</button>
<button class="btn1">停止动画</button>
<script>
var css = {
width: "70px",
opacity: 0.4,
marginLeft: "60px",
fontSize: "30px"
}
$(".btn").on("click",function(){
$(".box").animate(css, "slow", "linear", function(){
console.log("动画播放完毕")
})
})
$(".btn1").on("click",function(){
$(".box").stop(true,false);
})
</script>
</body>
</html>

动画效果的链式操作

  • 可以将animate()的队列功能使用链式方法呈现,因为每次使用animate()方法后返回的还是这个被查询的节点
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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div class="box">你好</div>
<button class="btn">播放动画</button>
<button class="btn1">停止动画</button>
<script>
$(".btn").on("click",function(){
$(".box").animate({right:'0px',width:'200px'},1000)
.animate({bottom:'0px',height:'200px'},1000)
.animate({left:'0px',width:'100px'},1000)
.animate({top:'0px',height:'100px'},1000)
console.log("动画播放完毕")
})
$(".btn1").on("click",function(){
$(".box").stop(true,false);
})
</script>
</body>
</html>

jQuery设置和获取元素内部HTML内容、text文本

获取内容、text文本

  • $(“.box”).html();获取元素内部的html内容,类似于innerHTML
  • $(“.box”).text();获取元素内部的text文本,类似于innerText
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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>jQuery</title>
</head>
<body>
<h1 id="header">我是<span>头部</span></h1>
<p id="footer">我是<strong>尾部</strong></p>
<button class="btn1">点我打印“我是头部”的html内容</button>
<button class="btn2">点我打印“我是头部”的文本内容</button>
<script>
$(".btn1").on("click",function(){
console.log($("#header").html())
});
$(".btn2").on("click",function(){
console.log($("#header").text())
});
</script>
</body>
</html>

jquery-3

设置内容、text文本

  • $(“.box”).html(“p设置了一个段落/p”);设置了元素内部的html内容,标签生效
  • $(“.box”).text(“设置了一个文本”);设置了元素内部的text文本,标签不生效
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>jQuery</title>
</head>
<body>
<h1 id="header">我是<span>头部</span></h1>
<p id="footer">我是<strong>尾部</strong></p>
<button class="btn3">点我设置“我是头部”的html内容</button>
<button class="btn4">点我设置“我是头部”的文本内容</button>
<script>
$(".btn3").on("click",function(){
$("#header").html('我是<em>内容</em>')
});
$(".btn4").on("click",function(){
$("#header").text('我是<em>内容</em>')
});
</script>
</body>
</html>

jquery-4

jQuery属性操作

表单内容value值

  • $(“input”).val();获得表单的value内容
  • $(“inout”).val(“改变后的表单”);设置表单
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" value="你好">
<script>
console.log($('input').val());
$('input').val('大家好');
</script>
</body>
</html>

jquery-5

元素的属性

  • $(“input”).attr(“type”);获取元素的 type 属性的值
  • $(“input”).attr(“type”, “password”);设置元素的type属性值为password
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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input class="text1" type="text">
<input class="text2" value="你设置后我变成了密码看不到了">
<input class="text3">
<script>
console.log($(".text1").attr("type"));
$(".text2").attr("type", "password");
$(".text3").attr({
"type": "password",
"placeholder": "请输入",
"name": "cg"
})
</script>
</body>
</html>

jquery-6

val()和attr(“value”)的区别

  • .val() 能够取到 针对text,hidden可输入的文本框的value值
  • .attr(‘value’) 可以取到html元素中所设置的属性 value的值,不能获取动态的如input type=”text” 的文本框手动输入的值

code:jquery实现二级菜单效果

jquery-6

explain

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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
<style>
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.menu {
background-color: red;
width: 200px;
}
.menu > li {
position: relative;
padding: 5px 10px;
color: #fff;
border-bottom: 1px solid #fff;
}
.sec-menu {
position: absolute;
top: 0;
left: 100%;
width: 200px;
border: 1px solid #000;
color: #000;
display: none;
}
.sec-menu > li {
float: left;
width: 90px;
padding: 5px;
}
</style>
</head>
<body>
<ul class="menu">
<li>
珠宝玉器
<ul class="sec-menu">
<li>翡翠</li>
<li>玉石</li>
<li>水晶</li>
<li>玛瑙</li>
<li>珍珠</li>
<li>钻石</li>
</ul>
</li>
<li>
珠宝玉器
<ul class="sec-menu">
<li>翡翠</li>
<li>玉石</li>
<li>水晶</li>
<li>玛瑙</li>
<li>珍珠</li>
<li>钻石</li>
</ul>
</li>
<li>
珠宝玉器
<ul class="sec-menu">
<li>翡翠</li>
<li>玉石</li>
<li>水晶</li>
<li>玛瑙</li>
<li>珍珠</li>
<li>钻石</li>
</ul>
</li>
<li>
珠宝玉器
<ul class="sec-menu">
<li>翡翠</li>
<li>玉石</li>
<li>水晶</li>
<li>玛瑙</li>
<li>珍珠</li>
<li>钻石</li>
</ul>
</li>
<li>
珠宝玉器
<ul class="sec-menu">
<li>翡翠</li>
<li>玉石</li>
<li>水晶</li>
<li>玛瑙</li>
<li>珍珠</li>
<li>钻石</li>
</ul>
</li>
</ul>
<script>
$('.menu').on('mouseenter','li',function(){
$(this).children('.sec-menu').css('display','block');
})
$('.menu').on('mouseleave','li',function(){
$(this).children('.sec-menu').css('display','none');
})
</script>
</body>
</html>

code:商品tab切换、添加更多效果

images

explain

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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
.clearfix:after {
content: "";
display: block;
clear: both;
}
.middle::before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.tab {
width: 800px;
border: 1px solid;
margin: 0 auto;
}
.tab-header > li {
float: left;
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
}
.tab-content > li {
text-align: center;
display: none;
}
.tab-content .shopping > li {
position: relative;
float: left;
width: 33.333%;
height: 250px;
}
.tab-content > li.see {
display: block;
}
.tab-content img {
width: 150px;
}
.tab-content .model {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(192,192,192,0.4);
display: none;
}
.tab-content .model .buy {
border: 1px solid #0ff;
padding: 5px 10px;
display: inline-block;
vertical-align: middle;
cursor: pointer;
}
.btn {
width: 100px;
height: 50px;
font-size: 24px;
background-color: #0ff;
border-radius: 5px;
border:none;
}
</style>
</head>
<body>
<div class="tab">
<ul class="tab-header clearfix">
<li>热门</li>
<li>珍宝首饰</li>
<li>奢侈品</li>
</ul>
<ul class="tab-content">
<li class="see">
<ul class="shopping clear">
<li>
<img src="http://img10.360buyimg.com/N3/jfs/t2242/92/1446546284/374195/9196ac66/56af0958N1a723458.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="http://img10.360buyimg.com/N3/jfs/t2242/92/1446546284/374195/9196ac66/56af0958N1a723458.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
</ul>
<button class="btn">更多</button>
</li>
<li>
<ul class="shopping clearfix">
<li>
<img src="https://img14.360buyimg.com/n1/jfs/t4555/318/3043855572/191419/8a41e4f8/58f5e592Na6c1839d.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img14.360buyimg.com/n1/jfs/t4555/318/3043855572/191419/8a41e4f8/58f5e592Na6c1839d.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img14.360buyimg.com/n1/jfs/t4555/318/3043855572/191419/8a41e4f8/58f5e592Na6c1839d.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img14.360buyimg.com/n1/jfs/t4555/318/3043855572/191419/8a41e4f8/58f5e592Na6c1839d.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img14.360buyimg.com/n1/jfs/t4555/318/3043855572/191419/8a41e4f8/58f5e592Na6c1839d.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img14.360buyimg.com/n1/jfs/t4555/318/3043855572/191419/8a41e4f8/58f5e592Na6c1839d.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
</ul>
<button class="btn">更多</button>
</li>
<li>
<ul class="shopping clearfix">
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
<li>
<img src="https://img11.360buyimg.com/n1/jfs/t4927/36/2232066517/100046/aa916922/58faf74dN226a1b30.jpg" alt="">
<div class="model middle">
<div class="buy ">立即抢购</div>
</div>
<p class="name">珂兰 黄金转运珠 猴哥款</p>
<p class="price">¥250</p>
</li>
</ul>
<button class="btn">更多</button>
</li>
</ul>
</div>
<script>
var $tabHeader = $('.tab-header');
var $tabContent = $('.tab-content');
var $btn = $('.btn');
$tabHeader.on('click','li',function(){
var index = $(this).index();
$tabContent.children('li').removeClass('see');
$tabContent.children('li').eq(index).addClass('see');
})
$('.shopping').on('mouseenter','li',function(){
$(this).children('.model').css('display','block');
})
$('.shopping').on('mouseleave','li',function(){
$(this).children('.model').css('display','none');
})
$btn.on('click',function(){
var products = [
{
img: 'http://img10.360buyimg.com/N3/jfs/t2242/92/1446546284/374195/9196ac66/56af0958N1a723458.jpg',
name: '珂兰 黄金手 猴哥款',
price: '¥405.00'
},{
img: 'http://img10.360buyimg.com/N3/jfs/t2242/92/1446546284/374195/9196ac66/56af0958N1a723458.jpg',
name: '珂兰 黄金转运珠 猴哥款',
price: '¥100.00'
},{
img: 'http://img10.360buyimg.com/N3/jfs/t2242/92/1446546284/374195/9196ac66/56af0958N1a723458.jpg',
name: '珂兰 黄金手链 3D猴哥款',
price: '¥45.00'
}
];
for(var i =0;i< products.length; i++){
var url = products[i].img;
var name = products[i].name;
var price = products[i].price;
var newList = [];
newList[i] = '<li>'
+ '<img src = "' + url + ' "alt="">'
+ '<div class = "model middle">'
+ '<div class = "buy">立即抢购</div>'
+ '</div>'
+ '<p class = "name">' + name + '</p>'
+ '<p class = "price">' + price + '</p>'
+ '</li>'
$(this).prev().append(newList[i]);
}
})
</script>
</body>
</html>

jQuery常用方法

$(document).ready()

  • DOM加载完毕后,指定一个函数来执行
1
2
3
4
5
6
7
$(document).ready(function(){
console.log("ready")
})
$(function(){
console.log("ready")
})
//二者是等价的

区别window.onload

  • window.onload只能编写一个,即使编写多个也只执行一个,而$(document).ready()则可编写多个并且都可得到执行
  • window.onload需要等到页面所有的元素(含图片的加载)加载完成后才执行,而$(document).ready()
    只需等到DOM准备就绪时就执行(不必等待所有元素加载完后再执行)
  • window.onload是原生js中的,而 $(document).ready()需在调用jquery库后才能使用
  • window.onload不可简写,而$(document).ready()可简写成

$node.html()、$node.text()

  • $node.html()是获取集合中第一个匹配元素的html内容;当()里面含有参数时则表示设置每个匹配元素的html内容
  • text()方法返回一个字符串,包含所有匹配元素的合并文本;当()里含有参数时,表示设置每个匹配元素的文本内容为指定文本内容
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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="demo-container1">
<div class="demo-box">Demonstration Box</div>
</div>
<div class="demo-container2">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>
<script>
$('div.demo-container1').html(); // <div class="demo-box">Demonstration Box</div>
$('div.demo-container2').text(); // Demonstration Box list item 1 list item 2
</script>
</body>
</html>

extend()

  • 将两个或更多对象的内容合并到第一个对象
  • $.extend( object1, object2)
  • 默认情况下是浅拷贝,想要深拷贝,就传入true参数,$.extend( true, object1, object2)
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">
<title>jQuery.extend demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="log"></div>
<script>
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1
$.extend( object1, object2 );
$( "#log" ).append( JSON.stringify( object1 ) );
</script>
</body>
</html>

images

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">
<title>jQuery.extend demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="log"></div>
<script>
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
$( "#log" ).append( JSON.stringify( object1 ) );
</script>
</body>
</html>

images

  • 浅拷贝,对象的相同属性的值会被替换,不相同的属性保留第一个;如果属性的值是对象,完全替换第二个的属性的值
  • 深拷贝,对象的相同属性的值会被替换,不相同的属性保留第一个;如果属性的值是对象,相同属性的值会被替换,不相同的属性保留第一个

链式调用

  • 使用jQuery方法时,对象方法返回的是对象本身,可以调用对此对象的其他jQuery方法,实现连续调用多个方法
1
$(".box").hide().show() //元素先隐藏,后展示

链式调用的实现原理

  • $(“选择器”).方法1(回调函数1).方法2(回调函数2).方法N(回调函数N);
  • 通过对象的方法最后将对象再返回回来(return this)继续被其他方法调用
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery</title>
<style type="text/css">
</style>
<script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
var Dog=function (name,age){
this.name=name;
this.age=age;
};
Dog.prototype={
getName:function(){
console.log(this.name);
return this
},
getAge:function(){
console.log(this.age);
return this
}
} ;
Dogs=function(name,age){
return new Dog(name,age);
} ;
Dogs("goutou",3).getName().getAge();
</script>
</body>
</html>

each()

  • 遍历一个jQuery对象,为每个匹配元素执行一个函数
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
<!DOCTYPE html>
<html>
<head>
<style>
ul { font-size:18px; margin:0; }
span { color:blue; text-decoration:underline; cursor:pointer; }
.example { font-style:italic; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
To do list: <span>(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Be merry</li>
</ul>
<script>
$( "span" ).click(function () {
$( "li" ).each(function(){
$( this ).toggleClass( "example" );
});
});
</script>
</body>
</html>

images

隐式迭代

  • jQuery的方法,返回一个jQuery对象遍历jQuery集合中的元素,被称为隐式迭代的过程。当这种情况发生时,它通常不需要显式地循环的.each()方法
1
2
3
4
5
6
7
8
9
10
$( "span" ).click(function () {
$( "li" ).each(function(){
$( this ).toggleClass( "example" );
});
});
// 等同于下面的效果,jQuery很多方法都是隐式迭代
$( "span" ).click(function () {
$( "li" ).toggleClass( "example" );
});

data()

  • data()实际上是对js对象或DOM对象的额外属性做一个集中管理,来避免内存泄漏
1
2
3
4
5
6
$.data(ele, name, data)
//是对ele元素附加数据
$().data(key, value)
//$().data(obj)是为jQuery对象中的所有DOM对象分别附加数据
$().data(key),
//$().data()从jQuery对象上读数据

jQuery常用DOM操作

给元素增加/删除class类

  • addClass(“active”):给元素 $node 添加 class active
  • $node.removeClass(“active”):给元素 $noed 删除 class active
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 在匹配的元素上加上'selected'样式
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 8px; font-size:16px; }
.selected { color:blue; }
.highlight { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
<script>
$("p").last().addClass("selected");
</script>
</body>
</html>

images

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 从匹配的元素中移除“blue”样式类
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 4px; font-size:16px; font-weight:bolder; }
.blue { color:blue; }
.under { text-decoration:underline; }
.highlight { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p class="blue under">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under">then</p>
<p class="blue under">Goodbye</p>
<script>$("p:even").removeClass("blue");</script>
</body>
</html>

images

展示元素/隐藏元素(上面有例子)

  • show():显示元素
  • hide():隐藏元素
  • css(“display”, “block”):给元素css属性设置display为block
  • css(“display”, “none”):给元素css属性设置display为none
  • fadeIn():通过淡入的方式显示匹配元素
  • fadeOut():通过淡出的方式隐藏匹配元素

获取/设置元素属性(上面有例子)

  • attr(“id”):获取元素的id属性的值
  • attr(“src”):获取元素的src属性的值
  • attr(“title”):获取元素的title属性的值
  • attr(“id”, “new-id”):设置元素的id属性值为new-id
  • attr(“src”, “new-src”):设置元素的src属性值为new-src
  • attr(“title”, “new-title”):设置元素的title属性值为new-title

给元素添加自定义属性

  • attr(“data-src”, “new-data”):设置元素的自定义data-src属性值为new-data

在父元素内部最开头添加元素

  • $ct.prepend($node):将参数内容插入到每个匹配元素的前面(元素内部)
  • $node.prependTo($ct):将所有元素插入到目标前面(元素内)
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
// 创建内容然后同时插入到好几个元素前面
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<script>
$('.inner').prepend('<p>Test</p>');
//等同于
$('<p>Test</p>').prependTo('.inner');
</script>
</body>
</html>

images

在父元素内部最末尾添加元素

  • $ct.append($node):将参数内容插入到每个匹配元素的后面(元素内部)
  • $node.prependTo($ct):将匹配的元素插入到目标元素的最后面(元素内部)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 创建内容然后同时插入到好几个元素后面
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<script>
$('.inner').append('<p>Test</p>');
//等同于
$('<p>Test</p>').prependTo('.inner');
</script>
</body>
</html>

images

删除元素

  • remove():将匹配元素集合从DOM中删除(同时移除元素上的事件及 jQuery 数据)
  • detach():从DOM中去掉所有匹配的元素(保存所有jQuery数据和被移走的元素相关联)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; margin:6px 0; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Call remove() on paragraphs</button>
<script>
$("button").click(function () {
$("p").remove();
});
</script>
</body>
</html>

images

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
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Attach/detach paragraphs</button>
<script>
$("p").click(function(){
$(this).toggleClass("off");
});
var p;
$("button").click(function(){
if ( p ) {
p.appendTo("body");
p = null;
} else {
p = $("p").detach();
}
});</script>
</body>
</html>

images

删除元素子节点

  • empty():从DOM中移除集合中匹配元素的所有子节点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 结果文本Hello文本被删除
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
</style>
</head>
<body>
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
<script>
$('.hello').empty();
</script>
</body>
</html>

images

父元素里设置html(上面有例子)

  • html():获取集合中第一个匹配元素的HTML内容或设置每一个匹配元素的html内容

获取、设置元素的宽度、高度

  • width():获取元素content的宽
  • width(200):设置元素content的宽
  • height():获取元素content的高
  • height(200):设置元素content的高
  • innerWidth():获取元素content+padding的宽
  • innerWidth(200):设置元素content+padding的宽
  • innerHeight():获取元素content+padding的高
  • innerHeight(200):设置元素content+padding的高
  • outerWidth():获取元素content+padding+border的宽
  • outerWidth(200):设置元素content+padding+border的宽
  • outerHeight():获取元素content+padding+border的高
  • outerHeight(200):设置元素content+padding+border的高
  • outerWidth(true):获取元素content+padding+border+margin的宽(不能设置)
  • outerHeight(true):获取元素content+padding+border+margin的高(不能设置)

images

获取/设置窗口滚动条垂直滚动距离

  • $(window).scrollTop()或者$(document).scrollTop():获取匹配的元素集合中第一个元素的当前垂直滚动条的位置
  • $(window).scrollTop(200)或者$(document).scrollTop(200):设置每个匹配元素的垂直滚动条位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 滚动条是在最顶部,或者这个元素没有可滚动的,那么这个数字是0
<!DOCTYPE html>
<html>
<head>
<style>
p { margin:10px;padding:5px;border:2px solid #666; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p><p></p>
<script>var p = $("p:first");
$("p:last").text( "scrollTop:" + p.scrollTop() );
</script>
</body>
</html>

images

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
// 设置一个div的scrollTop
<!DOCTYPE html>
<html>
<head>
<style>
div.demo {
background:#CCCCCC none repeat scroll 0 0;
border:3px solid #666666;
margin:5px;
padding:5px;
position:relative;
width:200px;
height:100px;
overflow:auto;
}
p { margin:10px;padding:5px;border:2px solid #666;width:1000px;height:1000px; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div class="demo"><h1>lalala</h1><p>Hello</p></div>
<script>$("div.demo").scrollTop(300);
</script>
</body>
</html>

images

获取/设置元素到根节点水平、垂直偏移距离

  • offset():获取到根节点水平、垂直偏移距离
  • offset({left: 500, top: 300}):设置到根节点水平、垂直偏移距离
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 使用第二个段落的位置
<!DOCTYPE html>
<html>
<head>
<style>
p { margin-left:10px; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );</script>
</body>
</html>

images

1
2
3
4
5
6
7
8
9
10
11
12
13
// 设置第二个段落的位置
<!DOCTYPE html>
<html>
<head>
<style>p { margin-left:10px; } </style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>$("p:last").offset({ top: 10, left: 30 });</script>
</body>
</html>

images

元素样式

  • css(‘background-color’):获取元素样式
  • css(‘backgroundColor’,’red’):设置元素样式
  • css({color: “red”,fontSize: “14px”}):设置多个元素样式
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
// 点击div,得到它的背景颜色
<!DOCTYPE html>
<html>
<head>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span id="result">&nbsp;</span>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>
<script>
$("div").click(function () {
var color = $(this).css("background-color");
$("#result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
});
</script>
</body>
</html>

images

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 通过mouseover事件改变一些段落的颜色为红色
<!DOCTYPE html>
<html>
<head>
<style>
p { color:blue; width:200px; font-size:14px; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Just roll the mouse over me.</p>
<p>Or me to see a color change.</p>
<script>
$("p").mouseover(function () {
$(this).css("color","red");
});
</script>
</body>
</html>

images

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
// 设置所有段落的文本颜色为红色背景为蓝色
<!DOCTYPE html>
<html>
<head>
<style>
p { color:green; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Move the mouse over a paragraph.</p>
<p>Like this one or the one above.</p>
<script>
$("p").hover(function () {
$(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
}, function () {
var cssObj = {
'background-color' : '#ddd',
'font-weight' : '',
'color' : 'rgb(0,40,244)'
};
$(this).css(cssObj);
});
</script>
</body>
</html>

images

遍历节点(上面有例子)

  • each():遍历一个jQuery对象,为每个匹配元素执行一个函数
1
2
3
4
$(document).each(function(){
var $text = $(this).text();
$(this).text($text+$text)
})

从父元素查找子元素

  • children(‘.item’):获得匹配元素集合中每个元素的子元素,选择器选择性筛选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 查找含有 "selected" 样式的 div 的所有子元素
<!DOCTYPE html>
<html>
<head>
<style>
body { font-size:16px; font-weight:bolder; }
p { margin:5px 0; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div>
<span>Hello</span>
<p class="selected">Hello Again</p>
<div class="selected">And Again</div>
<p>And One Last Time</p>
</div>
<script>$("div").children(".selected").css("color", "blue");</script>
</body>
</html>

images

查找元素的父元素

  • parent():取得匹配元素集合中,每个元素的父元素,可以提供一个可选的选择器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 查找每个段落的父元素,要求该父元素要带有 "selected" 样式
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div><p>Hello</p></div>
<div class="selected"><p>Hello Again</p></div>
<script>$("p").parent(".selected").css("background", "yellow");</script>
</body>
</html>

images

获取元素的数量

  • length:在jQuery对象中元素的数量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 计算 div 数量,点击后会增加一个 div
<!DOCTYPE html>
<html>
<head>
<style>
body { cursor:pointer; }
div { width:50px; height:30px; margin:5px; float:left;
background:green; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span></span>
<div></div>
<script>$(document.body).click(function () {
$(document.body).append($("<div>"));
var n = $("div").length;
$("span").text("There are " + n + " divs." +
"Click to add more.");
}).trigger('click'); // trigger the click to start</script>
</body>
</html>

images

获取元素的索引值

  • index():从匹配的元素中搜索给定元素的索引值,从0开始计数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 返回ID为bar的元素的索引值
<!DOCTYPE html>
<html>
<head>
<style>div { font-weight: bold; color: #090; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
<div></div>
<script>var listItem = $('#bar');
$('div').html( 'Index: ' + $('li').index(listItem) );</script>
</body>
</html>

images

code:用jQuery实现以下操作

  • 当点击$btn 时,让 $btn 的背景色变为红色再变为蓝色
  • 当窗口滚动时,获取垂直滚动距离
  • 当鼠标放置到$div 上,把$div 背景色改为红色,移出鼠标背景色变为白色
  • 当鼠标激活 input 输入框时让输入框边框变为蓝色,当输入框内容改变时把输入框里的文字小写变为大写,当输入框失去焦点时去掉边框蓝色,控制台展示输入框里的文字
  • 当选择 select 后,获取用户选择的内容

images

explain

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
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
.layout {
width: 600px;
margin: 0 auto;
border: 5px solid;
padding: 20px;
}
.btn {
width: 150px;
height: 120px;
font-size: 1.2em;
background-color: #fff;
margin-bottom: 50px;
}
.box {
width: 200px;
height: 300px;
border: 1px solid;
}
.scroll {
position: fixed;
left: 50%;
top: 30%;
}
#user {
width: 200px;
padding: 5px;
font-size: 1.5em;
border: 2px solid;
}
#city {
width: 100px;
height: 50px;
font-size: 1.2em;
border-radius: 3px;
}
#val {
color: #a00;
font-size: 1.2em;
}
</style>
</head>
<body>
<section class='layout'>
<h3>当点击$btn 时,让 $btn 的背景色变为红色再变为蓝色</h3>
<button class="btn">点我</button>
<h4 class="scroll">当窗口滚动时,获取垂直滚动距离<span>0</span>px</h4>
<h3>当鼠标放置到$div 上,把$div 背景色改为红色,移出鼠标背景色变为白色</h3>
<div class="box"></div>
<h3>当鼠标激活 input 输入框时让输入框边框变为蓝色,当输入框内容改变时把输入框里的文字小写变为大写,当输入框失去焦点时去掉边框蓝色,控制台展示输入框里的文字</h3>
<input id="user" type="text" placeholder="输入">
<h3>当选择 select 后,获取用户选择的内容:<span id="val"></span></h3>
<select name="city" id="city">
<option value="广州" selected>广州</option>
<option value="北京">北京</option>
<option value="杭州">杭州</option>
<option value="深圳">深圳</option>
<option value="上海">上海</option>
<option value="厦门">厦门</option>
</select>
</section>
<script>
var $btn = $('.btn');
var $div = $('.box');
var $user = $('#user');
var $city = $('#city');
$btn.on('click',function(){
$btn.css('background','#f00');
setTimeout(function(){
$btn.css('background','#00f')
},1000)
})
$(window).on('scroll',function(){
var scrollTop = $(window).scrollTop();
$('.scroll span').text(parseInt(scrollTop));
})
$div.on('mouseenter',function(){
$(this).css('background','#f00');
})
$div.on('mouseleave',function(){
$(this).css('background','#fff');
})
$user.on('focusin',function(){
$(this).css('borderColor','#00f');
})
$user.on('focusout',function(){
$(this).css('borderColor','#000');
console.log($(this).val());
})
$user.on('keypress',function(){
var val = $(this).val();
$(this).val(val.toUpperCase());
})
$('#val').text($city.val());
$city.on('change',function(){
$('#val').text($city.val());
})
</script>
</body>
</html>

code:jQuery ajax实现加载更多

images

explain

前端代码

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
<!DOCTYPE html>
<html lang="en">
<head>
<script src="/jquery-3.2.1.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
<style>
ul,
li {
list-style: none;
padding: 0;
margin: 0;
}
#news > li {
width: 600px;
border: 1px solid #000;
border-radius: 5px;
font-size: 24px;
margin: 0 auto;
text-align: center;
padding: 5px;
margin-top: 10px;
}
.btn{
width: 200px;
display: block;
margin: 0 auto;
margin-top: 20px;
font-size: 20px;
padding: 10px;
background-color: #0ff;
}
</style>
</head>
<body>
<ul id="news"></ul>
<button id="more" class="btn">加载更多</button>
<script>
var $news = $('#news');
var $btn = $('#more');
var $len = 3;
var lock = true;
$btn.on('click',function(){
if(!lock){
return;
}
lock = false;
var $index = $news.children('li').length;
$.ajax({
url: '/loadMore',
type: 'get',
data: {
len: $len,
index: $index
}
}).done(function(ret){
console.log(ret);
appendHtml(ret);
lock = true;
}).fail(function(){
console.log('服务器异常');
})
})
function appendHtml(news){
for(var i = 0; i < news.length; i++){
var $newsList = $("<li>" + news[i] + "</li>");
$news.append($newsList);
}
}
</script>
</body>
</html>

后端代码

1
2
3
4
5
6
7
8
9
router.get('/loadMore', function(req, res) {
var index = req.query.index; // 通过 req.query获取请求参数
var len = req.query.len;
var news = [];
for (var i = 0; i < len; i++) {
news[i] = '新闻' + (parseInt(index) + i + 1);
}
res.send(news);
})

常见组件

懒加载

图片懒加载的原理

  • 图片地址先放在自定义的属性data-src中,这样图片不会加载
  • 判断,当图片位置出现在窗口可视范围时候,获取data-src中的地址,写入src属性中生效加载

code:如何判断一个元素是否出现在窗口可视范围(浏览器的上边缘和下边缘之间,肉眼可视)。写一个函数 isVisible实现

explain

1
2
3
4
5
6
7
8
9
10
11
function isVisible($node){
var $offset = $node.offset().top;
var $scrollTop = $(window).scrollTop();
var $height = $node.outerHeight();
var $windowHeight = $(window).height();
if($windowHeight + $scrollTop > $offset && $scrollTop < $offset + $height){
return true
}else{
return false
}
}

code:当窗口滚动时,判断一个元素是不是出现在窗口可视范围。每次出现都在控制台打印 true 。用代码实现

explain

1
2
3
4
5
$(window).on("scroll", function(){
if(isVisible($node)){
console.log(true);
}
})

code:当窗口滚动时,判断一个元素是不是出现在窗口可视范围。在元素第一次出现时在控制台打印 true,以后再次出现不做任何处理。用代码实现

1
2
3
4
5
6
$(window).on("scroll", function(){
if(isVisible($node) && $node.not('.show').length > 0){
console.log(true);
$node.addClass("show");
}
})

轮播

实现原理

  • 轮播是把图片浮动水平排列
  • 然后设置一个视窗,大小等于一张图片
  • 视窗的overflow设置为hideen,溢出部分不可见
  • 点击下一页,所有图片就水平移动一个宽度

抽象出的函数组件

  • playNext():下一页
  • playPre():上一页
  • setBullet():设置底部的小方块