jQuery学习笔记
1 概述 1.1 JavaScript库
JavaScript库:即library,是一个封装好的特定的集合(方法和函数)。从封装一大堆函数的角度理解库,就是在这个库中,封装了很多预先定义好的函数在里面,比如动画animate、hide、show,比如获取元素等。 简单理解: 就是一个JS 文件,里面对我们原生js代码进行了封装,存放到里面。这样我们可以快速高效的使用这些封装好的功能了。 比如 jQuery,就是为了快速方便的操作DOM,里面基本都是函数(方法) 常见的JavaScript库
jQuery
Prototype
YUI
Dojo
Ext JS
移动端的zepto
这些库都是对原生 JavaScript 的封装,内部都是用 JavaScript 实现的
1.2 jQuery 的概念 jQuery 是一个快速、简洁的 JavaScript 库,其设计宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。
j — JavaScript;Query — 查询;意思就是查询js,把js中的DOM操作做了封装,可以快速的查询使用里面的功能
jQuery 封装了JavaScript常用的功能代码,优化了 DOM 操作、事件处理、动画设计和Ajax交互
学习jQuery本质: 就是学习调用这些函数(方法)
jQuery 出现的目的是加快前端人员的开发速度,我们可以非常方便的调用和使用它,从而提高开发效率
优点
2 jQuery 的基本使用 官网地址 https://jquery.com/
2.1 版本 各个版本的下载 https://code.jquery.com/
1x :兼容 IE 678 等低版本浏览器, 官网不再更新
2x :不兼容 IE 678 等低版本浏览器, 官网不再更新
3x :不兼容 IE 678 等低版本浏览器, 是官方主要更新维护的版本
2.2 jQuery 的入口函数 1、等着 DOM 结构渲染完毕即可执行内部代码,不必等到所有外部资源加载完成,jQuery 帮我们完成了封装
2、相当于原生 js中的 DOMContentLoaded
3、不同于原生 js中的 load 事件是等页面文档、外部的 js 文件、css文件、图片加载完毕才执行内部代码
4、更推荐使用第一种方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <style > div { width : 200px ; height : 200px ; background-color : pink; } </style > <script > $(function ( ) { $('div' ).hide(); }); </script > <div > </div >
2.3 jQuery 的顶级对象 $
2.4 jQuery 对象和 DOM 对象
注意:只有 jQuery 对象才能使用 jQuery 方法,DOM对象则使用原生的 JavaScirpt 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <style > div {width : 100px ;height : 100px ;background-color : pink;} </style > <div > </div > <span > </span > <script > var myDiv = document .querySelector('div' ); var mySpan = document .querySelector('span' ); console .dir(myDiv); $('div' ); $('span' ); console .dir($('div' )); </script >
DOM 对象与 jQuery 对象之间可以相互转换
因为原生 js 比 jQuery 更大,原生的一些属性和方法 jQuery 没有封装。要想使用这些属性和方法需要把 jQuery 对象转换为 DOM 对象才行
1、DOM 对象转换为 jQuery 对象$(DOM对象) 2、jQuery 对象转换为 DOM 对象(两种方式)$('div')[index] index 是索引号$('div').get(index) index 是索引号
3 jQuery 选择器 3.1 jQuery 基础选择器 原生 JS 获取元素方式很多,很杂,而且兼容性情况不一致,因此 jQuery 做了封装,使获取元素统一标准
$("选择器") 里面选择器直接写 CSS 选择器即可,但是要加引号
3.2 jQuery 层级选择器
隐式迭代(重要)
遍历内部 DOM 元素(伪数组形式存储)的过程就叫做隐式迭代
简单理解 :给匹配到的所有元素进行循环遍历,执行相应的方法,而不用我们再进行循环,简化操作,方便调用
1 2 3 4 5 6 7 8 9 <ul > <li > 相同的操作</li > <li > 相同的操作</li > <li > 相同的操作</li > </ul > <script > $("ul li" ).css("color" , "red" ); </script >
3.3 jQuery 筛选选择器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <ul > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > </ul > <ol > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > <li > 多个里面筛选几个</li > </ol > <script > $(function ( ) { $("ul li:first" ).css("color" , "red" ); $("ul li:eq(2)" ).css("color" , "blue" ); $("ol li:odd" ).css("color" , "skyblue" ); $("ol li:even" ).css("color" , "pink" ); }) </script >
3.4 jQuery 筛选方法(重点)
parents()获取所有祖先元素
parents("指定元素")获取指定祖先元素
$(this).index()获取当前元素索引号
重点记住parent() children() find() siblings() eq() hasClass()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <div class ="nav" > <p > 我是cess</p > <div > <p > 我是ssec</p > </div > </div > <script > $(function ( ) { console .log($(".son" ).parent()); $(".nav" ).children("p" ).css("color" , "yellowgreen" ); }); </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 <ol > <li > 我是ol 的li</li > <li > 我是ol 的li</li > <li class ="item" > 我是ol 的li</li > <li > 我是ol 的li</li > <li > 我是ol 的li</li > </ol > <ul > <li > 我是ol 的li</li > <li > 我是ol 的li</li > <li > 我是ol 的li</li > </ul > <div class ="current" > 俺有current</div > <div > 俺木有current</div > <script > $(function ( ) { $("ol .item" ).siblings("li" ).css("color" , "red" ); var index = 2 ; console .log($("div:first" ).hasClass("current" )); console .log($("div:last" ).hasClass("current" )); }); </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 <style > * {margin : 0 ;padding : 0 ;} li {list-style-type : none;} a {text-decoration : none;font-size : 14px ;} .nav {margin : 100px ;} .nav >li {position : relative;float : left;width : 80px ;height : 41px ;text-align : center;} .nav li a {display : block;width : 100% ;height : 100% ;line-height : 41px ;color : #333 ;} .nav >li >a :hover {background-color : #eee ;} .nav ul {display : none;position : absolute;top : 41px ;left : 0 ;width : 100% ; border-left : 1px solid #FECC5B ;border-right : 1px solid #FECC5B ;} .nav ul li {border-bottom : 1px solid #FECC5B ;} .nav ul li a :hover {background-color : #FFF5DA ;} </style > <ul class ="nav" > <li > <a href ="#" > 微博</a > <ul > <li > <a href ="" > 私信</a > </li > <li > <a href ="" > 评论</a > </li > <li > <a href ="" > @我</a > </li > </ul > </li > <li > <a href ="#" > 微博</a > <ul > <li > <a href ="" > 私信</a > </li > <li > <a href ="" > 评论</a > </li > <li > <a href ="" > @我</a > </li > </ul > </li > </ul > <script > $(function ( ) { $(".nav>li" ).mouseover(function ( ) { $(this ).children("ul" ).show(); }); $(".nav>li" ).mouseout(function ( ) { $(this ).children("ul" ).hide(); }) }); </script >
3.5 jQuery 里面的排他思想 想要多选一的效果,排他思想:当前元素设置样式,其余的兄弟元素清除样式。
1 2 $(this ).css("color" , "red" ); $(this ).siblings().css("color" , "" );
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <button > 快速</button > <button > 快速</button > <button > 快速</button > <script > $(function ( ) { $("button" ).click(function ( ) { $(this ).css("background" , "pink" ); $(this ).siblings("button" ).css("background" , "" ); }); }) </script >
3.6 链式编程 链式操作 是通过对象上的方法最后加上return this把对象再返回回来,对象就可以继续调用方法
链式编程是为了节省代码量,看起来更优雅
使用链式编程一定注意是哪个对象执行样式
1 $(this ).css('color' , 'red' ).sibling().css('color' , '' );
4 jQuery 样式操作 4.1 操作 css方法 jQuery 可以使用 css 方法来修改简单元素样式,也可以操作类,修改多个样式
1、参数只写属性名,则返回属性值
2、参数为(属性名,属性值),是设置一组样式,属性必须加引号,值如果是数字可以不用跟单位和引号
3、参数可以是对象形式,方便设置多组样式,大括号包含,类似JSON格式,属性可以不用加引号
1 2 3 $(this ).css("color" ); $(this ).css("color" , "red" ); $(this ).css({ "color" :"white" , "font-size" :"20px" });
4.2 设置类样式方法 作用等同于以前的classList,可以操作类样式, 注意操作类里面的参数不要加点
1、添加类
2、移除类
3、切换类
1 2 3 $("div" ).addClass("current" ); $("div" ).removeClass("current" ); $("div" ).toggleClass("current" );
4.3 类操作与 className 区别
原生 JS 中 className 会覆盖元素原先里面的类
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 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 <script src ="jquery.min.js" > </script > <style > * {margin : 0 ;padding : 0 ;} li {list-style-type : none;} .tab {width : 978px ;margin : 100px auto;} .tab_list {height : 39px ;border : 1px solid #ccc ;background-color : #f1f1f1 ;} .tab_list li {float : left;height : 39px ;line-height : 39px ;padding : 0 20px ; text-align : center;cursor : pointer;} .tab_list .current {background-color : #c81623 ;color : #fff ;} .item_info {padding : 20px 0 0 20px ;} .item {display : none;} </style > <body > <div class ="tab" > <div class ="tab_list" > <ul > <li class ="current" > 商品介绍</li > <li > 规格与包装</li > <li > 售后保障</li > <li > 商品评价(50000)</li > <li > 手机社区</li > </ul > </div > <div class ="tab_con" > <div class ="item" style ="display: block;" > 商品介绍模块内容 </div > <div class ="item" > 规格与包装模块内容 </div > <div class ="item" > 售后保障模块内容 </div > <div class ="item" > 商品评价(50000)模块内容 </div > <div class ="item" > 手机社区模块内容 </div > </div > </div > <script > $(function ( ) { $(".tab_list li" ).click(function ( ) { $(this ).addClass("current" ).siblings().removeClass("current" ); var index = $(this ).index(); console .log(index); $(".tab_con .item" ).eq(index).show().siblings().hide(); }); }) </script >
5 jQuery 效果 jQuery 给我们封装了很多动画效果,最为常见的如下
5.1 显示隐藏效果 显示 show([speed,[easing],[fn]])
隐藏 hide([speed,[easing],[fn]])
切换 toggle([speed,[easing],[fn]])
1、参数都可以省略, 无动画直接显示
2、speed 三种预定速度之一的字符串(’slow’, ‘normal’, ‘fast’)或表示动画时长的毫秒数值(如:1000)
3、easing (Optional) 用来指定切换效果,默认是“swing”,可用参数“linear”
4、fn 回调函数,在动画完成时执行的函数,每个元素执行一次
建议:平时一般不带参数,直接显示隐藏即可
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 <script src ="jquery.min.js" > </script > <style > div {width : 150px ;height : 300px ;background-color : pink;} </style > <button > 显示</button > <button > 隐藏</button > <button > 切换</button > <div > </div > <script > $(function ( ) { $("button" ).eq(0 ).click(function ( ) { $("div" ).show(1000 , function ( ) { alert(1); }); }) $("button" ).eq(1 ).click(function ( ) { $("div" ).hide(1000 , function ( ) { alert(1); }); }) $("button" ).eq(2 ).click(function ( ) { $("div" ).toggle(1000 ); }) }); </script >
5.2 滑动效果 下滑效果 slideDown([speed,[easing],[fn]])
上滑效果 slideUp([speed,[easing],[fn]])
滑动切换 slideToggle([speed,[easing],[fn]])
1、参数都可以省略, 无动画直接显示 2、speed 三种预定速度之一的字符串(’slow’, ‘normal’, ‘fast’)或表示动画时长的毫秒数值(如:1000) 3、easing (Optional) 用来指定切换效果,默认是“swing”(慢快慢),可用参数“linear”(匀速) 4、fn 回调函数,在动画完成时执行的函数,每个元素执行一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <script src ="jquery.min.js" > </script > <style > div {width : 150px ;height : 300px ;background-color : pink;display : none;} </style > <button > 下拉滑动</button > <button > 上拉滑动</button > <button > 切换滑动</button > <div > </div > <script > $(function ( ) { $("button" ).eq(0 ).click(function ( ) { $("div" ).slideDown(); }) $("button" ).eq(1 ).click(function ( ) { $("div" ).slideUp(500 ); }) $("button" ).eq(2 ).click(function ( ) { $("div" ).slideToggle(500 ); }); }); </script >
5.3 鼠标移进移出 hover([over,] out)
over 鼠标移到元素上要触发的函数(相当于mouseenter)
out 鼠标移出元素要触发的函数(相当于mouseleave)
如果只写一个函数,则鼠标经过和离开都会触发它
新浪下拉菜单改进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 $(".nav>li" ).mouseover(function ( ) { $(this ).children("ul" ).slideDown(200 ); }); $(".nav>li" ).mouseout(function ( ) { $(this ).children("ul" ).slideUp(200 ); }); $(".nav>li" ).hover(function ( ) { $(this ).children("ul" ).slideDown(200 ); }, function ( ) { $(this ).children("ul" ).slideUp(200 ); }); $(".nav>li" ).hover(function ( ) { $(this ).children("ul" ).slideToggle(); });
5.5 动画队列及停止排队方法 1、动画或效果队列 动画或者效果一旦触发就会执行,如果多次触发,就造成多个动画或者效果排队执行。 2、停止排队stop() 注意: stop() 写到动画或者效果的前面, 相当于停止结束上一次的动画
新浪下拉菜单改进2
1 2 3 4 $(".nav>li" ).hover(function ( ) { $(this ).children("ul" ).stop().slideToggle(); });
5.6 淡入淡出效果 淡入效果 fadeIn([speed, [easing], [fn]])
淡出效果 fadeOut([speed, [easing], [fn]])
淡入淡出 fadeToggle([speed, [easing], [fn]])
渐进方式调整到指定的不透明度 fadeTo(speed, opacity, [easing], [fn]])
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 <style > div {width : 150px ;height : 300px ;background-color : pink;display : none;} </style > <script src ="jquery.min.js" > </script > <button > 淡入效果</button > <button > 淡出效果</button > <button > 淡入淡出切换</button > <button > 修改透明度</button > <div > </div > <script > $(function ( ) { $("button" ).eq(0 ).click(function ( ) { $("div" ).fadeIn(1000 ); }) $("button" ).eq(1 ).click(function ( ) { $("div" ).fadeOut(1000 ); }) $("button" ).eq(2 ).click(function ( ) { $("div" ).fadeToggle(1000 ); }); $("button" ).eq(3 ).click(function ( ) { $("div" ).fadeTo(1000 , 0.5 ); }); });
5.7 自定义动画 animate animate(params, [speed], [easing], [fn])
params 想要更改的样式属性,以对象形式传递,必须写。 属性名可以不用带引号, 如果是复合属性则需要采取驼峰命名法 borderLeft。其余参数都可以省略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <style > div { position : absolute; width : 200px ; height : 200px ; background-color : pink; } </style > <button > 动起来</button > <div > </div > <script > $(function ( ) { $("button" ).click(function ( ) { $("div" ).animate({ left: 500, top: 300, opacity: .4, width: 500 }, 500); }) }) </script >
王者荣耀手风琴效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <script type ="text/javascript" > $(function ( ) { $(".king li" ).mouseenter(function ( ) { $(this ).stop().animate({ width: 224 }).find(".small" ).stop().fadeOut().siblings(".big" ).stop().fadeIn(); $(this ).siblings("li" ).stop().animate({ width: 69 }).find(".small" ).stop().fadeIn().siblings(".big" ).stop().fadeOut(); }) }); </script >
6 jQuery 属性操作 6.1 设置或获取元素固有属性值 prop() 所谓元素固有属性就是元素本身自带的属性,比如 元素里面的 href,比如 元素里面的 type
获取属性 prop("属性")
设置属性 prop("属性", "属性值")
6.2 设置或获取元素自定义属性值 attr() 用户自己给元素添加的属性,我们称为自定义属性。 比如给 div 添加 index =”1”
获取属性 attr("属性")
设置属性 attr("属性", "属性值")
6.3 数据缓存 data() data() 方法可以在指定的元素上存取数据,并不会修改 DOM 元素结构。一旦页面刷新,之前存放的数据都将被移除
获取数据 data("name")
附加数据 data("name', 'value")
同时,还可以读取 HTML5 自定义属性 data-index ,得到的是数字型
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 <a href ="http://www.itcast.cn" title ="都挺好" > 都挺好</a > <input type ="checkbox" name ="" id ="" checked > <div index ="1" data-index ="2" > 我是div</div > <span > 123</span > <script > $(function ( ) { console .log($("a" ).prop("href" )); $("a" ).prop("title" , "我们都挺好" ); $("input" ).change(function ( ) { console .log($(this ).prop("checked" )); }); console .log($("div" ).attr("index" )); $("div" ).attr("index" , 4 ); console .log($("div" ).attr("data-index" )); $("span" ).data("uname" , "andy" ); console .log($("span" ).data("uname" )); console .log($("div" ).data("index" )); }) </script >
7 jQuery 内容文本值 主要针对元素的内容还有表单的值操作
7.1 普通元素内容 html()( 相当于原生inner HTML) html() 获取元素的内容
html("内容") 设置元素的内容
7.2 普通元素文本内容 text() (相当与原生 innerText) text() 获取元素的内容
text("内容") 设置元素的内容
7.3 表单的值 val()( 相当于原生value) val() 获取元素的内容
val("内容") 设置元素的内容
toFixed(n)保留几位小数
8 jQuery 元素操作 8.1 遍历元素 jQuery 隐式迭代是对同一类元素做了同样的操作。 如果想要给同一类元素做不同操作,就需要用到遍历。
1、each(function(index, domEle){}) 方法遍历匹配的每一个元素。主要用DOM处理
2、each 里面的回调函数有2个参数
index 是每个元素的索引号
demEle 是每个DOM元素对象,不是jquery对象
3、所以要想使用jquery方法,需要给这个dom元素转换为jquery对象 $(domEle)
1 $("div" ).each(function (index, domEle ) {xxx;})
1、$.each(object,function(index, element) {})方法可用于遍历任何对象。主要用于数据处理,比如数组,对象
2、里面的函数有2个参数
index 是每个元素的索引号
element 遍历内容
1 $.each(object, function (index, element ) {xxx;})
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 <div > 1</div > <div > 2</div > <div > 3</div > <script > $(function ( ) { var sum = 0 ; var arr = ["red" , "green" , "blue" ]; $("div" ).each(function (i, domEle ) { $(domEle).css("color" , arr[i]); sum += parseInt ($(domEle).text()); }) console .log(sum); $.each({ name: "andy" , age: 18 }, function (i, ele ) { console .log(i); console .log(ele); }) }) </script >
8.2 创建元素 $("<li></li>") 动态的创建了一个
8.3 添加元素 1、内部添加 element.append("内容")把内容放入匹配元素内部最后面,类似原生 appendChild
element.prepend("内容") 把内容放入匹配元素内部最前面
反过来有appendTo() prependTo()
2、外部添加 element.after("内容")把内容放入目标元素后面
element.brfore("内容") 把内容放入目标元素前面
8.4 删除元素 element.remove() 删除匹配的元素(本身)
element.empty() 删除匹配的元素集合中所有的子节点,等价于 element.html("")
element.remove("") 清空匹配的元素内容
empt() 和 html(‘’’’) 作用等价,都可以删除元素里面的内容,只不过 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 <ul > <li > 原先的li</li > </ul > <div class ="test" > 原先的div</div > <script > $(function ( ) { var li = $("<li>后来创建的li</li>" ); $("ul" ).prepend(li); var div = $("<div>我是后妈生的</div>" ); $(".test" ).before(div); $("ul" ).html("" ); }) </script >
9 jQuery 尺寸、位置操作 9.1 jQuery 尺寸
以上参数为空,则是获取相应值,返回的是数字型
如果参数为数字,则是修改相应值
参数可以不必写单位
9.2 jQuery 位置 offset() 设置或获取元素偏移
offset() 方法设置或返回被选元素相对于文档的偏移坐标,跟父级没有关系
返回Object对象包含2个属性 left、top,offset().top 用于获取距离文档顶部的距离,offset().left 用于获取距离文档左侧的距离
可以设置元素的偏移:offset({ top: 10, left: 30 });
position() 获取元素偏移
scrollTop() scrollLeft() 设置或获取元素被卷去的头部和左侧
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 <style > body {height : 2000px ;} .back {position : fixed;width : 50px ;height : 50px ;background-color : pink; right : 30px ;bottom : 100px ;display : none;} .container {width : 900px ;height : 500px ;background-color : skyblue;margin : 400px auto;} </style > <script src ="jquery.min.js" > </script > <div class ="back" > 返回顶部</div > <div class ="container" > </div > <script > $(function ( ) { $(document ).scrollTop(100 ); var boxTop = $(".container" ).offset().top; $(window ).scroll(function ( ) { console .log($(document ).scrollTop()); if ($(document ).scrollTop() >= boxTop) { $(".back" ).fadeIn(); } else { $(".back" ).fadeOut(); } }); $(".back" ).click(function ( ) { $("body, html" ).stop().animate({ scrollTop: 0 }); }) }) </script >
10 jQuery 事件 10.1 jQuery 事件注册 element.事件(function(){})
10.2 jQuery 事件处理 1、on() 绑定事件 on() 方法在匹配元素上绑定一个或多个事件的事件处理函数
element.on(events, [selector], fn)
优势
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 <style > div {width : 100px ;height : 100px ;background-color : pink;} .current {background-color : purple;} </style > <script src ="jquery.min.js" > </script > <div > </div > <ul > <li > 我们都是好孩子</li > <li > 我们都是好孩子</li > <li > 我们都是好孩子</li > <li > 我们都是好孩子</li > <li > 我们都是好孩子</li > </ul > <ol > </ol > <script > $(function ( ) { $("div" ).on({ mouseenter: function ( ) { $(this ).css("background" , "skyblue" ); }, click: function ( ) { $(this ).css("background" , "purple" ); }, mouseleave: function ( ) { $(this ).css("background" , "blue" ); } }); $("div" ).on("mouseenter mouseleave" , function ( ) { $(this ).toggleClass("current" ); }); $("ul" ).on("click" , "li" , function ( ) { alert(11); }); $("ol" ).on("click" , "li" , function ( ) { alert(11); }) var li = $("<li>我是后来创建的</li>" ); $("ol" ).append(li); }) </script >
在此之前有 bind() live() delegate() 等方法来处理事件绑定或者事件委派,最新版本的请用 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 <style > * {margin : 0 ;padding : 0 } ul {list-style : none} .box {width : 600px ;margin : 100px auto;border : 1px solid #000 ;padding : 20px ;} textarea {width : 450px ;height : 160px ;outline : none;resize : none;} ul {width : 450px ;padding-left : 80px ;} ul li {line-height : 25px ;border-bottom : 1px dashed #cccccc ;display : none;} input {float : right;} ul li a {float : right;} </style > <script src ="jquery.min.js" > </script > <script > $(function ( ) { $(".btn" ).click(function ( ) { if ($(".txt" ).val() != "" ) { var li = $("<li></li>" ); li.html($(".txt" ).val() + "<a>删除</a>" ); $("ul" ).prepend(li) li.stop().slideDown(); $(".txt" ).val("" ); } }); $("ul" ).on("click" , "a" , function ( ) { $(this ).parent().slideUp(function ( ) { $(this ).remove(); }); }) }) </script > <div class ="box" id ="weibo" > <span > 微博发布</span > <textarea name ="" class ="txt" cols ="30" rows ="10" > </textarea > <button class ="btn" > 发布</button > <ul > </ul > </div >
2、off() 解绑事件 off() 方法可以移除通过 on() 方法添加的事件处理程序
1 2 3 $("p" ).off() $("p" ).off( "click" ) $("ul" ).off("click" , "li" );
如果有的事件只想触发一次, 可以使用one()来绑定事件
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 <style > div {width : 100px ;height : 100px ;background-color : pink;} </style > <script src ="jquery.min.js" > </script > <script > $(function ( ) { $("div" ).on({ click: function ( ) { console .log("我点击了" ); }, mouseover: function ( ) { console .log('我鼠标经过了' ); } }); $("ul" ).on("click" , "li" , function ( ) { alert(11); }); $("div" ).off("click" ); $("ul" ).off("click" , "li" ); $("p" ).one("click" , function ( ) { alert(11); }) }) </script > <div > </div > <ul > <li > 我们都是好孩子</li > <li > 我们都是好孩子</li > <li > 我们都是好孩子</li > </ul > <p > hello</p >
3、自动触发事件 trigger() 有些事件希望自动触发, 比如轮播图自动播放功能跟点击右侧按钮一致。可以利用定时器自动触发右侧按钮点击事件,不必鼠标点击触发
triggerHandler模式不会触发元素的默认行为,这是和前面两种的区别
1 2 3 4 5 6 7 8 9 element.click() element.trigger("事件" ) element.triggerHandler(事件) $("p" ).on("click" , function ( ) { alert("hi~" ); }); $("p" ).trigger("click" );
10.3 jQuery 事件对象 事件被触发,就会有事件对象的产生
阻止默认行为event.preventDefault()或者return false
阻止冒泡event.stopPropagation()
11 jQuery 其他方法 11.1 对象拷贝 如果想要把某个对象拷贝(合并) 给另外一个对象使用,此时可以使用 $.extend() 方法
$.extend([deep], target, object1, [objectN])
1、deep 如果设为 true 为深拷贝, 默认为 false 浅拷贝
2、target 要拷贝到的目标对象
3、object1 待拷贝到第一个对象的对象
4、objectN 待拷贝到第N个对象的对象
深浅拷贝
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 <script > $(function ( ) { var targetObj = { id: 0, msg: { sex: '男' } }; var obj = { id: 1, name: "andy" , msg: { age: 18 } }; $.extend(targetObj, obj); console .log(targetObj); targetObj.msg.age = 20; console .log(targetObj); console .log(obj); $.extend(true , targetObj, obj); targetObj.msg.age = 20; console .log(targetObj); console .log(obj); }) </script >
11.2 多库共存
jQuery使用$作为标识符,随着jQuery的流行,其他js库也会用这$作为标识符, 这样一起使用会引起冲突,需要一个解决方案,让jQuery 和其他的js库不存在冲突,可以同时存在,这就叫做多库共存。
jQuery 解决方案
1、把里面的 $ 符号 统一改为 jQuery。 比如 jQuery(''div'')
2、jQuery 变量规定新的名称$.noConflict() var xx = $.noConflict();
11.3 插件 jQuery 功能比较有限,想要更复杂的特效效果,可以借助于 jQuery 插件完成
注意 :这些插件也是依赖于jQuery来完成的,所以必须要先引入jQuery文件,因此也称为 jQuery 插件
1、jQuery 插件常用的网站 jQuery 插件库 http://www.jq22.com/ 懒加载
jQuery 之家 http://www.htmleaf.com/
2、jQuery 插件使用步骤 引入相关文件(jQuery 文件 和 插件文件)
复制相关html、css、js (调用插件)
3、jQuery 插件演示 1、瀑布流
2、图片懒加载(图片使用延迟加载在可提高网页下载速度。它也能帮助减轻服务器负载)
当我们页面滑动到可视区域,再显示图片。
我们使用jquery插件库 EasyLazyload。 注意,此时的js引入文件和js调用必须写到 DOM元素(图片)最后面
EasyLazyload.js(3 KB)
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 ;(function ($ ) { var defaults = { coverColor:"#dfdfdf" , coverDiv:"" , showTime:300 , offsetBottom:0 , offsetTopm:50 , onLoadBackEnd:function (index,dom ) {}, onLoadBackStart:function (index,dom ) {} } var srcList = [] var lazyLoadCoutn = 0 ; var windowHeight = $(window ).height(); var windowWidth = $(window ).width(); var lazyImgList = $("img[data-lazy-src]" ); var default_base64_src ="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" ; function getImgNaturalDimensions (src, callback,lazyLoadCoutn ) { var nWidth, nHeight var image = new Image() image.src = src; image.onload = function ( ) { callback(image.width, image.height); defaults.onLoadBackStart(lazyLoadCoutn,$("img[data-lazy-src]:eq(" +lazyLoadCoutn+")" )); } return [nWidth, nHeight]; } function showImg (lazyLoadCoutn,callback ) { var src = lazyImgList.eq(lazyLoadCoutn).attr("data-lazy-src" ) getImgNaturalDimensions(src, function ( ) { try { meng($("img[data-lazy-src]:eq(" +lazyLoadCoutn+")" ) ,lazyLoadCoutn,callback) }catch (error) { } },lazyLoadCoutn) } function meng (jDom,lazyLoadCoutn,callback ) { if (jDom.attr("data-comp" )){ return ; } jDom.css("visibility" ,"hidden" ); jDom.attr("src" ,jDom.attr("data-lazy-src" )) var w = jDom.width(); var h = jDom.height(); var offsetTop = jDom.offset().top; var offsetLeft = jDom.offset().left; jDom.css("visibility" ,"visible" ); $("body" ).append("<div class='meng-lazy-div" +lazyLoadCoutn+"' style='background-color: " +defaults.coverColor+";position:absolute;width:" +w+"px;height:" +h+"px;top:" +offsetTop+"px;left:" +offsetLeft+"px;z-index:500'>" +defaults.coverDiv+"</div>" ); noneM(lazyLoadCoutn,callback,jDom); jDom.attr("data-comp" ,"true" ); } function noneM (lazyLoadCoutn,callback,jDom ) { if (true ){ $(".meng-lazy-div" +lazyLoadCoutn).animate({opacity :"0" },defaults.showTime,function ( ) { $(this ).remove(); defaults.onLoadBackEnd(lazyLoadCoutn,jDom) callback(); }); } } function checkOffset ( ) { var scrollTop = $(document ).scrollTop(); var onlazyList = []; lazyImgList.each(function (index ) { var dom = $(this ); if (!dom.attr("data-comp" )){ if (dom.offset().top-scrollTop+defaults.offsetTopm>=0 &&dom.offset().top-scrollTop<(windowHeight+defaults.offsetBottom)){ onlazyList.push(index); } } }) if (onlazyList.length!=0 ){ showImg(onlazyList[0 ],function ( ) { checkOffset(); }); } } function range ( ) { checkOffset(); } function init (setting ) { defaults = $.extend(defaults,setting); lazyImgList.each(function ( ) { var sr = $(this ).attr("data-lazy-src" ); srcList.push(sr); $(this ).attr("src" ,default_base64_src); }); range(); window .onscroll=function ( ) { range() } } window .lazyLoadInit = init; })($)
EasyLazyload.min.js(2 KB)
1 !function (t ) {function o (o,a,i ) {var n,c,e=new Image;return e.src=o,e.onload=function ( ) {a(e.width,e.height),r.onLoadBackStart(i,t("img[data-lazy-src]:eq(" +i+")" ))},[n,c]}function a (a,n ) {var c=l.eq(a).attr("data-lazy-src" );o(c,function ( ) {try {i(t("img[data-lazy-src]:eq(" +a+")" ),a,n)}catch (t){}},a)}function i (o,a,i ) {if (!o.attr("data-comp" )){o.css("visibility" ,"hidden" ),o.attr("src" ,o.attr("data-lazy-src" ));var c=o.width(),e=o.height(),d=o.offset().top,f=o.offset().left;o.css("visibility" ,"visible" ),t("body" ).append("<div class='meng-lazy-div" +a+"' style='background-color: " +r.coverColor+";position:absolute;width:" +c+"px;height:" +e+"px;top:" +d+"px;left:" +f+"px;z-index:500'>" +r.coverDiv+"</div>" ),n(a,i,o),o.attr("data-comp" ,"true" )}}function n (o,a,i ) {t(".meng-lazy-div" +o).animate({opacity :"0" },r.showTime,function ( ) {t(this ).remove(),r.onLoadBackEnd(o,i),a()})}function c ( ) {var o=t(document ).scrollTop(),i=[];l.each(function (a ) {var n=t(this );n.attr("data-comp" )||n.offset().top-o+r.offsetTopm>=0 &&n.offset().top-o<s+r.offsetBottom&&i.push(a)}),0 !=i.length&&a(i[0 ],function ( ) {c()})}function e ( ) {c()}function d (o ) {r=t.extend(r,o),l.each(function ( ) {var o=t(this ).attr("data-lazy-src" );f.push(o),t(this ).attr("src" ,A)}),e(),window .onscroll=function ( ) {e()}}var r={coverColor :"#dfdfdf" ,coverDiv :"" ,showTime :300 ,offsetBottom :0 ,offsetTopm :50 ,onLoadBackEnd :function (t,o ) {},onLoadBackStart :function (t,o ) {}},f=[],s=t(window ).height(),l=(t(window ).width(),t("img[data-lazy-src]" )),A="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" ;window .lazyLoadInit=d}($);
3、全屏滚动(fullpage.js)
gitHub https://github.com/alvarotrigo/fullPage.js
中文翻译网站 http://www.dowebok.com/demo/2014/77/
4、bootstrap JS 插件 bootstrap 框架也是依赖于 jQuery 开发的,因此里面的 js插件使用 ,也必须引入 jQuery 文件
https://v3.bootcss.com/
12 todolist案例 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 <link rel ="stylesheet" href ="index.css" > <script src ="jquery.min.js" > </script > <script src ="todolist.js" > </script > <header > <section > <label for ="title" > ToDoList</label > <input type ="text" id ="title" name ="title" placeholder ="添加ToDo" required ="required" autocomplete ="off" /> </section > </header > <section > <h2 > 正在进行 <span id ="todocount" > </span > </h2 > <ol id ="todolist" class ="demo-box" > </ol > <h2 > 已经完成 <span id ="donecount" > </span > </h2 > <ul id ="donelist" > </ul > </section > <footer > Copyright © 2014 todolist.cn </footer > </body >
todolist.js
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 $(function ( ) { load(); $("#title" ).on("keydown" , function (event ) { if (event.keyCode === 13 ) { if ($(this ).val() === "" ) { alert("请输入您要的操作" ); } else { var local = getDate(); local.push({ title : $(this ).val(), done : false }); saveDate(local); load(); $(this ).val("" ); } } }); $("ol, ul" ).on("click" , "a" , function ( ) { var data = getDate(); var index = $(this ).attr("id" ); data.splice(index, 1 ); saveDate(data); load(); }); $("ol, ul" ).on("click" , "input" , function ( ) { var data = getDate(); var index = $(this ).siblings("a" ).attr("id" ); data[index].done = $(this ).prop("checked" ); saveDate(data); load(); }); function getDate ( ) { var data = localStorage .getItem("todolist" ); if (data !== null ) { return JSON .parse(data); } else { return []; } } function saveDate (data ) { localStorage .setItem("todolist" , JSON .stringify(data)); } function load ( ) { var data = getDate(); console .log(data); $("ol, ul" ).empty(); var todoCount = 0 ; var doneCount = 0 ; $.each(data, function (i, n ) { if (n.done) { $("ul" ).prepend("<li><input type='checkbox' checked='checked' > <p>" + n.title + "</p> <a href='javascript:;' id=" + i + " ></a></li>" ); doneCount++; } else { $("ol" ).prepend("<li><input type='checkbox' > <p>" + n.title + "</p> <a href='javascript:;' id=" + i + " ></a></li>" ); todoCount++; } }); $("#todocount" ).text(todoCount); $("#donecount" ).text(doneCount); } })
index.css
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 body { margin : 0 ; padding : 0 ; font-size : 16px ; background : #CDCDCD ; } header { height : 50px ; background : #333 ; background : rgba (47 , 47 , 47 , 0.98 ); } section { margin : 0 auto; } label { float : left; width : 100px ; line-height : 50px ; color : #DDD ; font-size : 24px ; cursor : pointer; font-family : "Helvetica Neue" , Helvetica, Arial, sans-serif; } header input { float : right; width : 60% ; height : 24px ; margin-top : 12px ; text-indent : 10px ; border-radius : 5px ; box-shadow : 0 1px 0 rgba (255 , 255 , 255 , 0.24 ), 0 1px 6px rgba (0 , 0 , 0 , 0.45 ) inset; border : none } input :focus { outline-width : 0 } h2 { position : relative; } span { position : absolute; top : 2px ; right : 5px ; display : inline-block; padding : 0 5px ; height : 20px ; border-radius : 20px ; background : #E6E6FA ; line-height : 22px ; text-align : center; color : #666 ; font-size : 14px ; } ol ,ul { padding : 0 ; list-style : none; } li input { position : absolute; top : 2px ; left : 10px ; width : 22px ; height : 22px ; cursor : pointer; } p { margin : 0 ; } li p input { top : 3px ; left : 40px ; width : 70% ; height : 20px ; line-height : 14px ; text-indent : 5px ; font-size : 14px ; } li { height : 32px ; line-height : 32px ; background : #fff ; position : relative; margin-bottom : 10px ; padding : 0 45px ; border-radius : 3px ; border-left : 5px solid #629A9C ; box-shadow : 0 1px 2px rgba (0 , 0 , 0 , 0.07 ); } ol li { cursor : move; } ul li { border-left : 5px solid #999 ; opacity : 0.5 ; } li a { position : absolute; top : 2px ; right : 5px ; display : inline-block; width : 14px ; height : 12px ; border-radius : 14px ; border : 6px double #FFF ; background : #CCC ; line-height : 14px ; text-align : center; color : #FFF ; font-weight : bold; font-size : 14px ; cursor : pointer; } footer { color : #666 ; font-size : 14px ; text-align : center; } footer a { color : #666 ; text-decoration : none; color : #999 ; } @media screen and (max-device-width : 620px ) { section { width : 96% ; padding : 0 2% ; } } @media screen and (min-width : 620px ) { section { width : 600px ; padding : 0 10px ; } }