jQuery API https://jquery.cuishifeng.cn/
1. 基础认知
1.1. js库
jsku是对原生JavaScript的封装,内部都是用JavaScript实现的,常见的js库有:jQuery,Prototype,YUI,Dojo,Ext JS,移动端的zepto
1.2. jQuery概念
jQuery是一个快速,简洁的JavaScript库,设计宗旨是”write less,Do More”,倡导写更少的代码,做更多的事情
j-JavaScript
query-查询
把js中的DOM操作封装,快速的查询使用里面的功能
jQuery封装了JavaScript常用的功能代码,优化了DOM操作,事件处理,Ajax交互
学习jQuery本质就是学习调用这些函数
1.3. jQuery下载
官网地址:https://jquery.com/
版本:
- 1x:兼容IE678,官网不再更新
- 2x:不兼容IE678,官网不再更新
1.4. 基本使用
引入script文件
1
| <script src="js/jquery-3.6.0.min.js"></script>
|
编写js代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <body> <div></div> <script> $("document").ready(function(){ $("div").hide(); }); $(function(){ $("div").hide(); }); </script> </body>
|
1.5. jQuery顶级对象 $
$
是jQuery的别称,在代码中可以使用jQuery代替 $
,通常直接使用$
1.6. jQuery对象 vs DOM对象
原生js获取的对象就是DOM对象
jQuery获取的对象就是jQuery对象
jQuery对象是利用$对DOM对象包装后产生的对象,用伪数组形式存储
两者不可混用
1.6.1. DOM对象转为jQuery对象
1 2
| var myvideo = document.querySelector("video"); $(myvideo);
|
1.6.2. jQuery对象转为DOM对象
1 2 3
| $('div')[index]
$('div')get(index)
|
2. 选择器
2.1. 基础选择器
名称 |
用法 |
描述 |
id选择器 |
$(‘#id’) |
获取指定id的元素 |
全选选择器 |
$(‘*’) |
匹配所有元素 |
类选择器 |
$(‘.class’) |
获取同一类class的元素 |
标签选择器 |
$(‘div’) |
获取同一类标签的所有元素 |
并集选择器 |
$(‘div,p,li’) |
选取多个元素 |
交集选择器 |
$(‘li.current’) |
交集元素 |
2.2. 层级选择器
名称 |
用法 |
描述 |
子代选择器 |
$(‘ul>li’) |
获取亲儿子层级的元素;注意,并不会获取孙子以下层级元素 |
后代选择器 |
$(‘ul li’) |
获取ul的所有li元素,包括孙子等 |
2.3. 筛选选择器
语法 |
用法 |
描述 |
:first |
$(li:first) |
获取第一个li元素 |
:last |
$(li:last) |
获取最后一个li元素 |
:eq(index) |
$(li:eq(index)) |
获取索引号为index的li元素,索引号从0开始 |
:odd |
$(li:odd) |
获取索引号为奇数的li元素 |
:even |
$(li:even) |
获取索引号为偶数的li元素 |
2.4. 筛选方法
语法 |
用法 |
描述 |
parent() |
$('li').parent() |
父级 |
children(selector) |
$('ul').children('li') |
相当于$('ul>li') ,最近一级 |
find(selector) |
$('ul').find('li') |
相当于$('ul li') ,后代选择器 |
siblings(selector) |
$('.first').siblings('li') |
查找兄弟节点,不包括自身 |
nextAll([expr]) |
$('li').nextAll(') |
查找当前元素之后所有同辈元素 |
prevAll([expr]) |
$('li').prevAll() |
查找当前元素之前所有同辈元素 |
hasClass(class) |
$('div').hasClass("protected") |
检查当前元素是否含有某个特定的类,如果有,返回true |
eq(index) |
$('li').eq(2) |
相当于 $(li:eq(2)) ,index从0开始 |
2.5. 元素索引号
2.6. 排他思想
1 2 3 4 5 6 7 8
| $(function(){ $('button').click(function(){ $(this).css("background-color","pink"); $(this).siblings("button").css("background-color",""); }); });
|
2.7. 案例:轻触转换
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <style> aside{ float: left; } aside ul{ list-style: none; margin: 0; padding: 0; } aside ul li{ width: 50px; height: 50px; text-align: center; font-size: 15px; line-height: 50px; border: 1px solid #000; } .content{ float: left; width: 250px; height: 258px; border: 1px solid #000; } .content div{ width: 100%; height: 100%; text-align: center; display: none; } .content div:first-child{ display: block; } </style> </head> <body> <aside> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </aside> <div class="content"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div> <script> $('aside li').mouseenter(function(){ var div = $('.content>div').eq($(this).index()); div.show(); div.siblings().hide(); }); </script> </body> </html>
|
3. 样式操作
3.1. 操作css方法
参数只写属性名,则返回属性值
参数是属性名,属性值,逗号分隔,属性必须加引号,值如果是数字可以不加单位
1
| $(this).css("color","red");
|
参数可以是对象形式,属性名和属性值冒号隔开,属性不用加引号
1 2 3 4
| $(this).css( {"color":"red", "font-size":"20" });
|
3.2. 设置类样式方法
添加类
1
| $('div').addClass('current');
|
删除类
1
| $('div').removeClass('current');
|
切换类
1
| $('div').toggleClass('current');
|
4. jQuery效果
4.1. 事件切换 hover()
当鼠标移动到一个匹配的元素上面时,会触发指定的第一个函数
当鼠标移出这个元素时,会触发指定的第二个函数
可以直接是 hover(fn)
当鼠标移到元素上或移出元素时触发执行的事件函数
4.2. 停止排队 stop()
动画或者效果一旦触发就会执行,如果多次触发,造成多个动画或者效果排队执行
stop()
写到动画或者效果的前面,相当于停止结束上一次的动画
4.3. 显示隐藏
4.3.1. show()
显示隐藏的匹配元素
1
| show([speed],[easing],[fn])
|
- 参数可以省略,无动画直接显示
speed
:三种预定义速度之一的字符串(slow,normal,fast),或表示动画时长的毫秒数值(如:100)
easing
:指定切换效果,默认是swing,可用参数linear
fn
:回调函数,动画完成时执行的函数,每个元素执行一次
4.3.2. hide()
隐藏显示的元素
1
| hide([speed],[easing],[fn])
|
4.3.3. toggle()
切换
1
| toggle([speed],[easing],[fn])
|
4.4. 滑动
4.4.1. slideDown()
通过高度变化(向下增大)来动态地显示所有匹配的元素,在显示完成后可选地触发一个回调函数
1
| slideDown([speed],[easing],[fn])
|
4.4.2. slideUp()
通过高度变化(向上减小)来动态地隐藏所有匹配的元素,在隐藏完成后可选地触发一个回调函数
1
| slideUp([speed],[easing],[fn])
|
4.4.3. slideToggle()
通过高度变化来切换所有匹配元素的可见性,并在切换完成后可选地触发一个回调函数
1
| slideToggle([speed],[easing],[fn])
|
4.5. 淡入淡出
4.5.1. fadeIn()
通过不透明度的变化来实现所有匹配元素的淡入效果,并在动画完成后可选地触发一个回调函数
1
| fadeIn([speed],[easing],[fn])
|
4.5.2. fadeOut()
通过不透明度的变化来实现所有匹配元素的淡出效果,并在动画完成后可选地触发一个回调函数
1
| fadeOut([speed],[easing],[fn])
|
4.5.3. fadeToggle()
通过不透明度的变化来开关所有匹配元素的淡入和淡出效果,并在动画完成后可选地触发一个回调函数
1
| fadeToggle([speed],[easing],[fn])
|
4.5.4. fadeTo()
把所有匹配元素的不透明度以渐进方式调整到指定的不透明度,并在动画完成后可选地触发一个回调函数
1
| fadeTo([speed],opacity,[easing],[fn])
|
4.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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <style> .content{ width: 500px; height: 250px; margin: 0 auto; } .content div{ float: left; width: 25%; height: 125px; background-color: pink; border: 1px solid #999; box-sizing: border-box; } </style> </head> <body> <div class="content"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> <script> $(".content div").hover(function(){ $(this).siblings().stop().fadeTo(100,.5); },function(){ $(this).siblings().stop().fadeTo(100,1); }) </script> </body> </html>
|
4.7. 自定义动画
1
| animate(params,[speed],[easing],[fn]);
|
这个函数的关键在于指定动画形式及结果样式属性对象。这个对象中每个属性都表示一个可以变化的样式属性(如“height”、“top”或“opacity”)。
⚠️注意:所有指定的属性必须用骆驼形式,比如用marginLeft代替margin-left.
param
:一组包含作为动画属性和终值的样式属性和及其值的集合
speed
:三种预定速度之一的字符串(“slow”,”normal”, or “fast”)或表示动画时长的毫秒数值(如:1000)
easing
:要使用的擦除效果的名称(需要插件支持).默认jQuery提供”linear” 和 “swing”.
fn
:在动画完成时执行的函数,每个元素执行一次。
4.8. 案例:手风琴效果
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <style> .content ul{ list-style: none; } .content ul li{ position: relative; float: left; width: 69px; height: 69px; margin-right: 20px; } .big{ width: 224px; height: 69px; display: none; background-color: blue; } .small{ width: 69px; height: 69px; position: absolute; left: 0; top: 0; background-color: purple; } .content li.current{ width: 224px; } .content li.current .big{ display: block; } .content li.current .small{ display: none; } </style> </head> <body> <div class="content"> <ul> <li class="current"> <div class="big">1</div> <div class="small">1</div> </li> <li> <div class="big">2</div> <div class="small">2</div> </li> <li> <div class="big">3</div> <div class="small">3</div> </li> <li> <div class="big">4</div> <div class="small">4</div> </li> </ul> </div> <script> $(".content ul li").hover(function(){ $(this).animate({ width: 224 },200).find(".small").stop().fadeOut().siblings(".big").stop().fadeIn(); $(this).siblings("li").animate({ width: 69 },200).find(".big").stop().fadeOut().siblings(".small").stop().fadeIn(); }); </script> </body> </html>
|
5. 属性操作
5.1. 元素固有属性值 prop()
元素本身自带的属性
获取属性值
设置属性值
1
| element.prop("属性名","属性值");
|
5.2. 自定义属性值attr()
用户自己给元素添加的属性,如<div data-index="1"></div>
获取属性值
设置属性值
1
| element.attr("属性名","属性值");
|
可以获取H5的自定义属性 data-index -> attr("data-index")
5.3. 数据缓存data()
指定的元素上存取数据,并不会修改DOM元素结构,一旦页面刷新,之前存放的数据都将被移除
附加数据
1
| element.data("key","value");
|
获取数据
可以获取H5的自定义属性 data-index -> data("index")
6. 内容文本值
6.1. 获取元素内容html()
1 2 3 4 5 6 7
|
$("div").html();
$("div").html("123");
|
6.2. 获取元素文本内容text()
1 2 3 4 5 6 7 8
| $("div").text();
$("div").text();
$("div").text("123");
|
6.3. 获取表单值val()
7. 元素操作
7.1. 遍历 each()
1
| $("div").each(function(idx,elem){});
|
7.2. $.each()
1 2
| $.each($("div"),function(idx,elem){});
|
可用于遍历任何对象。主要用于数据处理,比如数组,对象
7.3. 创建元素
内部添加
1 2 3 4 5
| var li = $("<li></li>");
ul.append(li);
ul.prepend(li);
|
外部添加
1 2 3 4 5
| var div = $("<div></div>");
$(".test").after(div);
$(".test").before(div);
|
7.4. 删除元素
1 2 3 4 5 6
| $("ul").remove();
$("ul").empty(); $("ul").html();
|
7.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 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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <style> html,body{ width: 100%; } .cart{ width: 80%; margin: 0 auto; } .cart .cart-top, .cart .cart-bottom, .cart .cart-item{ width: 100%; height: 100px; overflow: hidden; border-bottom: 2px dotted #999; } .cart-item .imgdiv{ float: left; } .cart-item .price,.numdiv,.sum{ float: left; } .cart-item .price{ margin-left: 50%; } .cart-item .imgdiv{ width: 100px; height: 80%; margin: 10px; background-color: pink; } .cart-top span, .cart-bottom span{ display: block; font-size: 16px; color: #333; margin: 35px; float: left; } .cart-bottom p{ float: left; } .cart-bottom p, .cart-item p{ font-size: 20px; color: red; margin: 30px; } .cart-top input, .cart-bottom input, .cart-item .sub,input,.add{ float: left; width: 30px; height: 30px; margin-top: 30px; border: 1px solid #999; text-align: center; font-size: 20px; } .cart-item input[type='text']{ box-sizing: border-box; width: 40px; font-size: 15px; } .cart-bottom input[type='checkbox'], .cart-top input[type='checkbox'], .cart-item input[type='checkbox']{ box-sizing: border-box; width: 15px; } .cart-bottom a, .cart-item a{ text-decoration: none; color: #333; font-size: 20px; margin: 30px; display: block; float: left; cursor: pointer; } .cart-bottom .sum-num{ display: inline-block; float: none; margin: 0 20px; } .cart-bottom .num{ margin-left: 30%; } .check-cart-item{ background-color: rgba(215, 91, 91, 0.103); } </style> </head> <body> <div class="cart"> <div class="cart-top"> <input type="checkbox" name="" id="" class="checkall"> <span>全选</span> </div> <div class="cart-item"> <input type="checkbox" name="" id="" checked class="checkitem"> <div class="imgdiv"></div> <p class="price">¥12.60</p> <div class="numdiv"> <button class="sub">-</button> <input type="text" value="1" class="txt"> <button class="add">+</button> </div> <p class="sum">¥12.60</p> <a class="removeitem">删除</a> </div> <div class="cart-item"> <input type="checkbox" name="" id="" class="checkitem"> <div class="imgdiv"></div> <p class="price">¥2.90</p> <div class="numdiv"> <button class="sub">-</button> <input type="text" value="1" class="txt"> <button class="add">+</button> </div> <p class="sum">¥2.90</p> <a class="removeitem">删除</a> </div> <div class="cart-item"> <input type="checkbox" name="" id="" class="checkitem"> <div class="imgdiv"></div> <p class="price">¥10.60</p> <div class="numdiv"> <button class="sub">-</button> <input type="text" value="1" class="txt"> <button class="add">+</button> </div> <p class="sum">¥10.60</p> <a class="removeitem">删除</a> </div> <div class="cart-bottom"> <input type="checkbox" name="" id="" class="checkall"> <span>全选</span> <a class="delete">删除选中商品</a> <p class="num">已经选<span class="sum-num">1</span>件商品</p> <p class="sum">总价</p> <p class="price">¥12.60</p> </div> </div> <script> $(function(){ $(".cart .checkall").change(function(){ var flag = $(this).prop("checked"); $(".cart-item .checkitem").prop('checked',flag); $(".cart .checkall").prop('checked',flag); getSum(); checkchangeback(); }); function checkchange(){ var num = $(".cart-item .checkitem:checked").length; var len = $(".cart-item .checkitem").length; if(num==len&&num!=0){ $(".cart .checkall").prop('checked',true); }else{ $(".cart .checkall").prop('checked',false); } checkchangeback(); } checkchangeback(); function checkchangeback(){ $(".cart-item .checkitem").each((idx,obj)=>{ if($(obj).prop('checked')){ $(obj).parent().addClass("check-cart-item"); }else{ $(obj).parent().removeClass("check-cart-item"); } }) } $(".cart-item .checkitem").change(function(){ checkchange(); getSum(); });
$(".cart-item .sub").click(function(){
var num = $(this).siblings("input").val(); if(num==1){ return false; } num--; calprice(this,num); }); $(".cart-item .add").click(function(){ var num = $(this).siblings("input").val(); num++; calprice(this,num); }); $(".cart-item .numdiv .txt").change(function(){ calprice(this,$(this).val()); getSum(); }); function calprice(obj,num){ $(obj).parent().siblings(".checkitem").prop("checked",true); checkchange();
$(obj).siblings("input").val(num); var price = $(obj).parent().siblings(".price").text().substr(1); var ans = parseFloat(price)*num; ans = ans.toFixed(2); $(obj).parent().siblings(".sum").text("¥"+ans); getSum(); } getSum(); function getSum(){ var sum = 0; var num = 0; $(".cart-item .checkitem:checked").each((idx,elem)=>{ var price = $(elem).siblings(".sum").text().substr(1); sum+=parseFloat(price);
var cnt = $(elem).siblings(".numdiv").children(".txt").val(); num+=parseInt(cnt); }); $(".cart-bottom .price").text("¥"+sum.toFixed(2)); $(".cart-bottom .num .sum-num").text(num); checkchange(); }
$(".cart-item .removeitem").click(function(){ $(this).parents(".cart-item").remove(); getSum(); });
$(".cart-bottom a").click(function(){ $(".cart-item .checkitem:checked").each((idx,elem)=>{ $(elem).parents(".cart-item").remove(); getSum(); }); }); }); </script> </body> </html>
|
8. 尺寸操作
语法 |
用法 |
width()/height() |
取得匹配元素宽度和高度值,只算width,height |
innerWidth()/innerHeight() |
包含padding |
outerWidth()/outerHeight() |
包含padding,border |
outerWidth(true)/outerHeight(true) |
包含padding,border,margin |
可以添加参数,修改元素尺寸,不用加单位
9. 位置操作
9.1. 设置或获取元素偏移offset()
设置或返回被选元素相对于文档
的偏移坐标,跟父级无关
方法有2个属性left,top。
offset().top:获取距离文档顶部的距离
offset().left:获取距离文档左侧的距离
1 2 3 4 5 6 7 8 9
| $("div").offset().top; $("div").offset().left;
$("div").offset({ left: 200, top: 200 });
|
9.2. 获取元素偏移position()
返回被选元素相对于带有定位的父级
的偏移坐标,父级没有定位时,以文档为准
无法修改
元素被卷去的头部和左侧
1 2 3 4 5 6 7 8
| $(window).scroll(function(){ if($(document).scrollTop() >= $("div").offset().top){ $("span").stop().fadeIn(); }else{ $("span").stop().fadeOut(); } });
|
页面停在指定位置
1
| $(document).scrollTop(100);
|
返回顶部 - 带动画
1 2 3 4 5
| $(".back").click(function(){ $("body,html").stop().animate({ scrollTop: 0 }) });
|
9.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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <style> html,body{ width: 100%; } .header, div[class^='content']{ width: 80%; margin: 0 10% 20px 10%; font-size: 40px; color: #fff; text-align: center; } .header{ height: 400px; line-height: 400px; background-color: rgb(114, 114, 219); } .goback{ position: fixed; bottom: 50%; transform: translateY(50%); right: 5px; width: 5%; height: 200px; background-color: pink; display: none; } .goback ul{ list-style: none; margin: 0; padding: 0; } .goback li{ height: 40px; line-height: 40px; box-sizing: border-box; text-align: center; color: #fff; border-bottom: 1px solid #666; cursor: pointer; } .goback li:last-child{ border-bottom: none; } .goback li.current{ background-color: rgb(235, 78, 78); }
</style> </head> <body> <div class="header">header</div> <div class="content1">content1</div> <div class="content2">content2</div> <div class="content3">content3</div> <div class="content4">content4</div> <div class="content5">content5</div> <div class="goback"> <ul> <li class="current">content1</li> <li>content2</li> <li>content3</li> <li>content4</li> <li>content5</li> <li>返回顶部</li> </ul> </div> <script> $("div[class^='content']").each((i,elem)=>{ $(elem).css({ "height":400+100*i+'px', "line-height":400+100*i+'px', "background-color":"rgb(255,"+(i*50)+","+(i*50)+")" }); });
showdiv(); var flag = true; function showdiv(){ var content1top = $(".content1").offset().top; var content2top = $(".content2").offset().top; var top = $(document).scrollTop(); if(top<content1top){ $(".goback").stop().fadeOut(); } else if(top>=content1top && top<content2top){ $(".goback").stop().fadeIn(10).animate({ height: 200 },10); }else{ console.log(content1top,content2top,top); $(".goback").stop().fadeIn(10).animate({ height: 240 },10); } if(flag){ $("div[class^='content']").each(function(idx,elem){ if($(document).scrollTop()>=$(elem).offset().top){ $(".goback li").eq(idx).addClass("current").siblings().removeClass("current"); } }); } } $(window).scroll(function(){ showdiv(); });
$(".goback li").click(function(){ flag = false; var idx = $(this).index(); $(this).addClass("current"); $(this).siblings().removeClass("current"); if(idx==$(".goback li").length-1){ $("body,html").animate({ scrollTop:0 },function(){ flag = true; }) }else{ var top = $("div[class^='content']").eq(idx).offset().top; $("body,html").stop().animate({ scrollTop:top },function(){ flag = true; }); } }); </script> </body> </html>
|
10. 事件
10.1. on()
匹配元素上绑定一个或多个事件处理函数
1
| element.on(event,[selector],[data],fn);
|
events
:一个或多个用空格分隔的事件类型和可选的命名空间,如”click”或”keydown.myPlugin” 。
selector
:一个选择器字符串用于过滤器的触发事件的选择器元素的后代。如果选择的< null或省略,当它到达选定的元素,事件总是触发。
data
:当一个事件被触发时要传递event.data给事件处理函数。
fn
:该事件被触发时执行的函数。 false 值也可以做一个函数的简写,返回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
| function myHandler(event) { alert(event.data.foo); } $("p").on("click", {foo: "bar"}, myHandler)
$(".header").on({ mouseenter:function(){ $(this).css("background","red"); }, click:function(){ $(this).css("background","green"); }, mouseleave:function(){ $(this).css("background","blue"); } })
$(".header").on("mouseenter mouseleave",function(){ $(this).css("background","red");
})
$("ul").on("click","li",function(){ $(this).css("background","red"); })
|
10.1.1. 案例:微博发布
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"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <style> .box{ width: 200px; } .box ul{ list-style: none; } .box ul li{ overflow: hidden; } .box ul a{ text-decoration: none; color: #000; float: right; } .box ul span{ float: left; } </style> </head> <body> <div class="box"> <span>微博发布</span> <textarea name="" id="" cols="30" rows="10"></textarea> <button>发布</button> <ul></ul> </div>
<script> $(function(){ $(".box button").on("click",function(){ var li = $("<li></li>"); var content = $(".box textarea").val(); $(".box textarea").val(""); content = "<span>"+content+"</span><a href='javascript:;'>删除</a>"; li.html(content);
$(".box ul").prepend(li); li.slideDown(); }); $(".box ul").on("click","li a",function(){ $(this).parent().slideUp(function(){ $(this).remove(); }); }); }) </script> </body> </html>
|
10.2. off()
在选择元素上移除一个或多个事件的事件处理函数
1
| element.off(event,[selector],fn);
|
删除所有事件
删除特定事件
1 2 3 4
| $("p").off("click");
$("ul").off("click","li");
|
10.3. one()
为每一个匹配元素的特定事件(像click)绑定一个一次性的事件处理函数
1
| element.one(type,[data],fn);
|
10.4. 事件对象
1 2 3
| element.one(type,[data],function(e){ });
|
阻止默认行为 e.preventDefault();
阻止冒泡行为 e.stopPropagation();
11. 对象拷贝 extend()
1
| $.extend([deep],target,object1,[objectN]);
|
targetObj={name: "AAA",age: 18}
1 2 3 4 5 6
| var targetObj = {}; var obj = { name: 'AAA', age: 18 }; $.extend(targetObj,obj);
|
empty = { validate: true, limit: 5, name: "bar" }
1 2 3 4
| var empty = {}; var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; var settings = jQuery.extend(empty, defaults, options);
|
empty = { id: 1, limit: {age: 19}}
复制的只是对象的地址,原内容改变,值就改变
1 2 3 4 5 6 7 8 9 10 11 12
| var empty = { id: 0 }; var options = { id: 1, limit: { age: 18 } }; var settings = jQuery.extend(empty, options); options.limit.age=19; console.log(empty);
|
empty = { id: 1, limit: {age: 18}}
深拷贝
1 2 3 4 5 6 7 8 9 10 11 12
| var empty = { id: 0 }; var options = { id: 1, limit: { age: 18 } }; var settings = jQuery.extend(true,empty, options); options.limit.age=19; console.log(empty);
|
12. 多库共存
jQuery使用$
作为标识符,其他js库也可能使用这个标识符,会引起冲突
可以改为jQuery("div")
也可以
1 2
| var xx = $.noConflict(); xx("button").on("click",function(){});
|
13. jQuery插件
http://www.jq22.com/
http://www.htmleaf.com/
14. Ajax
Asynchronous JavaScript And XML 异步JavaScript和XML
在网页中利用XMLHttpRequest对象和服务器进行数据交互的方式就是ajax
14.1. $.get()
1
| $.get(url,[data],[callback]);
|
含义
参数名 |
参数类型 |
是否必选 |
说明 |
url |
string |
是 |
请求资源地址 |
data |
object |
否 |
请求资源期间要携带的参数 |
callback |
function |
否 |
请求成功是的回调函数 |
14.2. $.post()
1
| $.post(url,[data],[callback]);
|
14.3. $.ajax()
1
| $.ajax({type,url,[data],[callback]});
|
15. 表单
15.1. 监听提交事件
1 2 3
| $("form").submit(function(){});
$("form").on("submit",function(){});
|
15.2. 阻止表单默认提交行为
1 2 3 4
| $("form").on("submit",function(e){ e.preventDefault(); });
|
15.3. 获取表单数据
serialize()
每个表单元素必须添加name属性
1 2 3 4 5 6 7 8
| $("form").on("submit",function(e){ e.preventDefault(); var val = $(this).serialize(); console.log(arr); });
|