jQuery
简介
jQuery 是一个 JavaScript 库。jQuery 是一个“写的更少,但做的更多”的轻量级 JavaScript 库。
一、引入jQuery
1、<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <!--CDN引用jQuery--> 2、<script src="jquery.js"></script> <!--jQuery下载后通过目录引用--> 3、<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"> </script> <!--引用,官网指定的引用-->
如果使用引用方法引入jquery,建议找到可靠的源
二、选择器
1、通过id查找元素
HTML文件 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="i1">id=i1</div> <script src="jquery.js"></script> </body> </html> console调试结果 $("#i1") #通过jquery获取id为i1的标签 jQuery.fn.init [div#i1, context: document, selector: "#i1"] $("#i1")[0] #把jquery转换为dom标签 <div id="i1">id=i1</div> var i1 = document.getElementById("i1") #通过Dom获取标签 undefined i1 <div id="i1">id=i1</div> $(i1) #把Dom标签转换为jquery对象 jQuery.fn.init [div#i1, context: div#i1]
2、通过标签查找元素
$("div") //找到所有div标签的元素
3、通过样式查找元素
$(".myClass") //得到样式myClass的元素
4、组合选择器selector1,selector2,selectorN查找元素
$("div,span") //找到所有div和span标签,注意选择器之间用逗号隔开
5、查找所有元素
$("*") //查找所有元素
6、层级选择器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> <label>Name:</label> <input name="name" /> <fieldset> <label>Newsletter:</label> <input name="newsletter" /> </fieldset> </form> <input name="none" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!--CDN引用jQuery--> </body> </html> $("form input") //找到form标签下的所有input标签 结果:[ <input name="name" />, <input name="newsletter" /> ] $("form > input") //找到form标签下的子标签(input) [ <input name="name" /> ] $("label + input") //找到所有紧接着label的input标签 [ <input name="name" />, <input name="newsletter" /> ] $("form ~ input") //找到所有与form标签同级别的input标签 [ <input name="none" /> ] 注意:上面示例只要为有效选择器即可
7、基本筛选器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!--CDN引用jQuery--> </body> </html> $("li:first") //获取匹配的第一个元素 $("li:last") //获取匹配的最后一个元素 $("li:eq(1)") //匹配一个给定索引值的元素,从0开始计数 $("li:gt(1)") //匹配所有大于给定索引值的元素,从0开始计数 $("li:lt(2)") //匹配所有小于给定索引值的元素,从0开始计数 :even //匹配所有索引值为偶数的元素,从 0 开始计数 :odd //匹配所有索引值为奇数的元素,从 0 开始计数 :not(selector) //去除所有与给定选择器匹配的元素 :header //匹配如 h1, h2, h3之类的标题元素
还有一些关于内容、可见性选择器详见:http://jquery.cuishifeng.cn/index.html
8、属性选择器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul id = "i1"> <li>list item 1</li> <li>list item 2</li> <li id = "item3">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!--CDN引用jQuery--> </body> </html> [attribute] //匹配包含给定属性的元素 例:$("[id]") //匹配有id属性的元素 $("ul[id]") //查找所有含有 id 属性的ul元素 [attribute=value] //匹配给定的属性是某个特定值的元素 [attribute^=value] //匹配给定的属性是以某些值开始的元素 [attribute$=value] //匹配给定的属性是以某些值结尾的元素 [attribute!=value] //匹配所有不含有指定的属性,或者属性不等于特定值的元素。 [attribute*=value] //匹配给定的属性是以包含某些值的元素 [selector1][selector2][selectorN] //复合属性选择器,需要同时满足多个条件时使用。
9、表单选择器
表单选择器可以用属性选择器代替。这里列举
表单 :input :text :password //匹配所有密码框 :radio :checkbox :submit :image :reset :button :file 表单对象属性 :enabled // 匹配所有可用元素 :disabled //匹配所有不可用元素 :checked //匹配所有选中的被选中元素(复选框、单选框等,select中的option),对于select元素来说,获取选中推荐使用 :selected :selected// 匹配所有选中的option元素
多选,反选,取消示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" value="全选"> <input type="button" value="反选"> <input type="button" value="取消"> <table border="1" cellspacing="0"> <thead> <tr> <th>选项</th> <th>IP地址</th> <th>端口</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> </tbody> </table> <script src="jquery.js"></script> <script> $(":button:first").click( function () { $(":checkbox").prop("checked",true); //prop如果只有一个参数,获取值(prop("checked")),两个参数设置值(prop("checked",true)), } ); $(":button:last").click( function () { $(":checkbox").prop("checked",false); } ); $(":button:eq(1)").click( //为标签绑定事件 function () { $(":checkbox").each(function () { //each循环元素 /*if($(this).prop("checked")){ $(this).prop("checked",false); }else{ $(this).prop("checked",true); }*/ //jquery 实现 /* if (this.checked){ this.checked = false; }else{ this.checked = true; }*/ //DOM实现 //三元运算 var = v 条件?真值:假值 var v = $(this).prop("checked")?false:true; $(this).prop("checked",v); }) } ) </script> </body> </html>
二、筛选器
在选择器中,有了解到一些基本的筛选器,但是很多情况,上面的筛选器都满足不了。
菜单栏示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .header{ background-color: aqua; } .content{ min-height: 50px; } .hide{ display: none; } </style> </head> <body> <div style="height: 400px;width: 200px;border: 1px solid #dddddd"> <div class="item"> <div class="header">标题一</div> <div class="content">内容</div> </div> <div class="item"> <div class="header">标题二</div> <div class="content hide">内容</div> </div> <div class="item"> <div class="header">标题三</div> <div class="content hide">内容</div> </div> <div class="item"> <div class="header">标题四</div> <div class="content hide"><span >内容</span></div> </div> </div> <script src="jquery.js"></script> <script> //为每个样式为header标签绑定一个click事件 $(.header).click(function(){}) //得到当前点击的标签$(this) //当前点击的标签的下一个标签(内容),并且为此标签删除样式 //当前点击的标签的父标签,以及所有兄弟标签的子标签中的内容标签,且为此标签添加样式 $(".header").click(function(){ //$(this +div) //这里如果用基本的筛选器已经满足不了,这里会报错,因为this是个标签对象,div又需要用引号包裹,所以这里冲突 $(this).next().removeClass("hide"); // $(this).parent().siblings().children(".content").addClass("hide"); //parent父标签,siblings所有兄弟标签 // var v = $(this).parent().siblings().children("span"); //children所有孩子标签 // var v1 = $(this).parent().siblings().find("span"); //find 子子孙孙标签 // console.log(v); // console.log(v1); $(this).parent().siblings().find(".content").addClass("hide"); //find,搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。 }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul id = "i1"> <li>list item 1</li> <li>list item 2</li> <li class = "item3">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!--CDN引用jQuery--> </body> </html> $("li").first() //获取第一个元素,与$("li:first")区别为,$("li:first")为字符串的形式获取,$("li").first() 对象形式获取 $("li").last() //获取最后一个元素 $("li").eq(1) //获取当前链式操作中第N个jQuery对象,返回jQuery对象,可以为负数 hasClass(class) //检查当前的元素是否含有某个特定的样式,如果有,则返回true。 filter(expr|obj|ele|fn) //筛选出与指定表达式匹配的元素集合。用逗号分隔多个表达式 is(expr|obj|ele|fn) //根据选择器、DOM元素或 jQuery 对象来检测匹配元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true。 slice(start, [end]) //相当于切片 not(expr|ele|fn) //从匹配元素的集合中删除与指定表达式匹配的元素 has(expr|ele) //保留包含特定后代的元素,去掉那些不含有指定后代的元素。 map(callback) //将一组元素转换成其他数组(不论是否是元素数组),callback给每个元素执行的函数
children([expr]) //取得一个包含匹配的元素集合中每一个元素的所有子元素的元素集合。在孩子中查找,表达式可选 find(expr|obj|ele) //搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。注意,这里一定要指定表达式,在子子孙孙中查找 parent([expr]) //取得一个包含着所有匹配元素的唯一父元素的元素集合。可以使用表达式来筛选.[父元素] parents([expr]) //得一个包含着所有匹配元素的祖先元素的元素集合(不包含根元素)。可以通过一个可选的表达式进行筛选。[祖先元素] next([expr]) //取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。 nextAll([expr]) //查找当前元素之后所有的同辈元素。 nextUntil([exp|ele][,fil]) //查找当前元素之后所有的同辈元素,直到遇到匹配的那个元素为止 同理还有prev,prevAll,prevUntil,parentsUntil siblings([expr]) //取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合。可以用可选的表达式进行筛选。 add(expr|ele|html|obj[,con]) //把与表达式匹配的元素添加到jQuery对象中。这个函数可以用于连接分别与两个表达式匹配的元素结果集。
筛选器整理的有点乱,可详见:http://jquery.cuishifeng.cn/index.html
模态对话框示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .modal{ position: fixed; top:50%; left:50%; height: 400px; width: 500px; border: 1px solid #dddddd; margin-left:-200px ; margin-top: -200px; background-color:#dddddd ; z-index: 10; } .shadow{ position: fixed; top:0; bottom: 0; right: 0; left: 0; background-color: black; opacity: 0.7; z-index: 9; } .hide{ display: none; } </style> </head> <body> <div class="shadow hide"> </div> <!--遮罩层--> <div class="modal hide"> <div> <input name="hostname" type="text" > <input name="port" type="text"> </div> <div> <button id="i2">取消</button> </div> </div> <!--弹出框--> <button id="i1">添加</button> <table border="1"> <thead> <tr> <th>ip</th> <th>端口</th> <th>选项</th> </tr> </thead> <tbody> <tr> <td>1.1.1.1</td> <td>80</td> <td ><a class="edit">编辑</a> | <a> 删除</a></td> </tr> <tr> <td>2.2.2.2</td> <td>10</td> <td ><a class="edit">编辑</a> | <a> 删除</a></td> </tr> <tr> <td>3.3.3.3</td> <td>20</td> <td > <a class="edit">编辑</a> | <a> 删除</a> </td> </tr> </tbody> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $("#i1").click(function () { $("input[name='hostname'],input[name='port']").val(""); //添加前先清空对话框里面的内容 $(".modal,.shadow").removeClass("hide"); }); $("#i2").click(function () { $(".modal,.shadow").addClass("hide"); }); $(".edit").click(function () { var v = $(this).parent().prevAll(); //找到要编辑的端口和地址 $("input[name = 'hostname']").val(v.get(0).innerText); //v.get(0)为dom对象,要用dom方法来获取文本,或则可以转换城jquery对象,通过text()方法来获取文本内容 $("input[name = 'port']").val(v.get(1).innerText); $(".modal,.shadow").removeClass("hide"); console.log(v.get(0).innerText); }) </script> </body> </html>
模态对话框改进
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .modal{ position: fixed; top:50%; left:50%; height: 400px; width: 500px; border: 1px solid #dddddd; margin-left:-200px ; margin-top: -200px; background-color:#dddddd ; z-index: 10; } .shadow{ position: fixed; top:0; bottom: 0; right: 0; left: 0; background-color: black; opacity: 0.7; z-index: 9; } .hide{ display: none; } </style> </head> <body> <div class="shadow hide"> </div> <!--遮罩层--> <div class="modal hide"> <div> <input name="hostname" type="text" > <input name="port" type="text"> </div> <div> <button id="i2">取消</button> </div> </div> <!--弹出框--> <button id="i1">添加</button> <table border="1"> <thead> <tr> <th>ip</th> <th>端口</th> <th>选项</th> </tr> </thead> <tbody> <tr> <td target="hostname">1.1.1.1</td> <td target = "port">80</td> <td ><a class="edit">编辑</a> | <a> 删除</a></td> </tr> <tr> <td target="hostname">2.2.2.2</td> <td target = "port">10</td> <td ><a class="edit">编辑</a> | <a> 删除</a></td> </tr> <tr> <td target="hostname">3.3.3.3</td> <td target = "port">20</td> <td > <a class="edit">编辑</a> | <a> 删除</a> </td> </tr> </tbody> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $("#i1").click(function () { $("input[name='hostname'],input[name='port']").val(""); //添加前先清空对话框里面的内容 $(".modal,.shadow").removeClass("hide"); }); $("#i2").click(function () { $(".modal,.shadow").addClass("hide"); }); $(".edit").click(function () { var v = $(this).parent().prevAll(); //找到要编辑的端口和地址 //对选项循环,并且自定义target来确定填的内容 v.each(function () { var target = $(this).attr("target"); var val = $(this).text(); console.log(val); $("input[name = '"+target+"']").val(val) //字符串拼接 }); $(".modal,.shadow").removeClass("hide"); }) </script> </body> </html>
三、属性及样式操作
1、属性操作
//attr专门用于自定义属性 $(..).attr('k') 获得n属性的值 $(..).attr('k','v') 设置n属性的值为v $(..).removeAttr('k') 移除n属性 //专门用于checkbox,radio $(..).prop('k') 获得n属性的值 $(..).prop('k','v') 设置n属性的值为v $(..).removeProp('k') 移除n属性 如: $("input[type='checkbox']").prop("disabled", false); $("input[type='checkbox']").prop("checked", true);
2、CSS类操作
addClass(class|fn) //添加样式
removeClass([class|fn]) //移除样式
toggleClass(class|fn[,sw]) //如果存在该样式就移除,如果不存在就添加
3、HTML代码/文本/值
//html()对应DOM中的innerHTML //text()对应DOM中的innerText //val()对应DOM中的value $(..).html() //获得第一个匹配元素的html内容 $(..).html("v") //获得匹配元素的html为v $(..).text() //取得所有匹配元素的内容。 $(..).text("v") //设置元素内容的文本 $(..).val() //获得匹配元素的当前值。该方法大多用于 input 元素,获取value属性的值 $(..).val("v") //设置值
TAB切换菜单示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .menu{ height: 30px; border: 1px solid #dddddd; line-height: 30px; } .menu-item{ border-right:1px solid black ; padding: 0 10px; float: left; cursor: pointer; /*当鼠标放到该标签出现小手的样式*/ } .content{ min-height: 200px; border: 1px solid #dddddd; } .hide{ display: none; } .active{ background-color: antiquewhite; } </style> </head> <body> <div style="width: 700px;margin: 0 auto"> <div class="menu"> <div class="menu-item active">菜单一</div> <div class="menu-item">菜单二</div> <div class="menu-item">菜单三</div> </div> <div class="content"> <div class="content-item">内容一</div> <div class="content-item hide">内容二</div> <div class="content-item hide">内容三</div> </div> </div> <script src="jquery.js"></script> <script> $(".menu").children().click(function () { $(this).addClass('active'); $(this).siblings().removeClass('active'); console.log($(this).index()) ; //返回在同辈元素的索引位置,从0开始 var index = $(this).index(); //获取当前点击的标签的索引位置 //取得内容标签,根据索引位置移除样式,并为其兄弟标签添加样式 $(this).parent().next().children().eq(index).removeClass("hide").siblings().addClass("hide"); }) </script> </body> </html>
四、文档处理
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text"> <input type="button" value="添加" name="add"> <input type="button" value="删除" name="del"> <input type="button" value="复制" name="copy"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!--CDN引用jQuery--> <script> $("input[name='add']").click(function () { var val = $("input[type='text']").val(); if (val){ li_tag = document.createElement('li'); //DOM的方式创建标签,jquery没有提供创建标签的方法 $(li_tag).text(val); //设置值 $("ul").append(li_tag); //向每个匹配的元素内部追加内容。 // $("ul").prepend(li_tag); //向每个匹配的元素内部前置内容。 // $(li_tag).prependTo("ul"); //把所有匹配的元素前置到另一个、指定的元素元素集合中 // $(li_tag).appendTo("ul li:eq(2)"); //把所有匹配的元素追加到另一个指定的元素元素集合中。 // $("ul").after(li_tag); //在每个匹配的元素之后插入内容。 // $("ul").before(li_tag); //在每个匹配的元素之前插入内容。 // $(li_tag).insertAfter("ul"); //把所有匹配的元素插入到另一个、指定的元素元素集合的后面。 // $("ul").insertBefore(li_tag); //把所有匹配的元素插入到另一个、指定的元素元素集合的前面。 } }); $("input[name='del']").click(function () { var index = $("input[type='text']").val(); console.log(typeof index); //判断类型 console.log(typeof parseInt(index)); if (index<$("ul li").length){ // $("ul li").eq(index).remove(); //从DOM中删除所有匹配的元素。 $("ul li").eq(index).empty(); //删除匹配的元素集合中所有的子节点。 } }); $("input[name='copy']").click(function () { var index = $("input[type='text']").val(); if (index<$("ul li").length){ var v = $("ul li").eq(index).clone(); //克隆一份 $("ul").append(v); } }); </script> </body> </html>
模态对话框终极版
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .modal{ position: fixed; top:50%; left:50%; height: 400px; width: 500px; border: 1px solid #dddddd; margin-left:-200px ; margin-top: -200px; background-color:#dddddd ; z-index: 10; } .shadow{ position: fixed; top:0; bottom: 0; right: 0; left: 0; background-color: black; opacity: 0.7; z-index: 9; } .hide{ display: none; } </style> </head> <body> <div class="shadow hide"> </div> <!--遮罩层--> <div class="modal hide"> <div id="i3"> <input name="hostname" type="text" > <input name="port" type="text"> </div> <div> <button id="i2">取消</button> <button id="confirm">确定</button> </div> </div> <!--弹出框--> <button id="i1">添加</button> <table border="1"> <thead> <tr> <th>ip</th> <th>端口</th> <th>选项</th> </tr> </thead> <tbody> <tr> <td target="hostname">1.1.1.1</td> <td target = "port">80</td> <td ><a class="edit">编辑</a> | <a class="del"> 删除</a></td> </tr> <tr> <td target="hostname">2.2.2.2</td> <td target = "port">10</td> <td ><a class="edit">编辑</a> | <a class="del"> 删除</a></td> </tr> <tr> <td target="hostname">3.3.3.3</td> <td target = "port">20</td> <td > <a class="edit">编辑</a> | <a class="del"> 删除</a> </td> </tr> </tbody> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $("#i1").click(function () { $("input[name='hostname'],input[name='port']").val(""); //添加前先清空对话框里面的内容 $(".modal,.shadow").removeClass("hide"); }); $("#i2").click(function () { $(".modal,.shadow").addClass("hide"); }); function edit() { var v = $(this).parent().prevAll(); //找到要编辑的端口和地址 //对选项循环,并且自定义target来确定填的内容 v.each(function () { var target = $(this).attr("target"); var val = $(this).text(); console.log(val); $("input[name = '"+target+"']").val(val) //字符串拼接 }); $(".modal,.shadow").removeClass("hide"); } function cancel() { $(this).parent().parent().remove(); } $(".del").click(cancel); $("#confirm").click(function () { var tr_tag = document.createElement("tr"); $("#i3").children().each( //循环input标签 function () { var val = $(this).val(); var td_tag = document.createElement("td"); $(td_tag).text(val); var attr_name = $(this).attr('name'); //获取name属性 $(td_tag).attr('target',attr_name); //设置target属性 console.log(tr_tag); $(tr_tag).append(td_tag); //添加标签至tr } ); var td_tag = document.createElement("td"); td_tag.innerHTML = '<a class="edit">编辑</a> | <a class="del"> 删除</a>'; $(tr_tag).append(td_tag); $("tbody").append(tr_tag); $(".edit").on("click",edit); //重新绑定事件 $(".del").click(cancel); }); $(".edit").on("click",edit); </script> </body> </html>
五、CSS样式操作
1、样式操作
$("选择器").css("css样式名") //获取样式 $("选择器").css("css样式名","value") //设置样式值
点赞操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container{ padding: 40px; border-bottom: 1px solid #dddddd; } .item{ position: relative; width: 35px; } </style> </head> <body> <div class="container"> <div class = "item"> <span>赞</span></div> </div> <div class="container"> <div class = "item" > <span>赞</span></div> </div> <div class="container"> <div class = "item"> <span>赞</span></div> </div> <script src="jquery.js"></script> <script> $(".item span").click(function () { var span_tag = document.createElement("span"); var fontsize = 15; var top = 0; var right = 0; var opacity = 1; $(span_tag).text("+1"); $(span_tag).css("position","absolute"); $(span_tag).css("color","green"); $(span_tag).css("right",right+"px"); $(span_tag).css("top",top+"px"); $(span_tag).css("font-size",fontsize+"px"); $(span_tag).css("opacity",opacity); $(this).after(span_tag); var obj = setInterval(function () { fontsize = fontsize+5; top = top-5; right = right-5; opacity = opacity-0.2; $(span_tag).css("right",right+"px"); $(span_tag).css("top",top+"px"); $(span_tag).css("font-size",fontsize+"px"); $(span_tag).css("opacity",opacity); if (opacity <0){ //清除定时器 clearInterval(obj); $(span_tag).remove(); } },40) }) </script> </body> </html>
2、高度操作
html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="height: 200px;width: 100px;overflow: auto"> <span> asdasd</span><span> asdasd</span><span> asdasd</span> <span> asdasd</span><span> asdasd</span><span> asdasd</span> <span> asdasd</span><span> asdasd</span><span> asdasd</span> <span> asdasd</span><span> asdasd</span><span> asdasd</span> <span> asdasd</span><span> asdasd</span><span> asdasd</span> </div> <div style="width: 300px;height: 100px;position: relative;border: 1px solid red"> <div id="i1" style="background-color: black;height: 40px;width: 40px;position: absolute;right: 0"></div> </div> <div style="height: 1000px"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </body> </html>
scrollTop([val]):获取匹配元素相对滚动条顶部的偏移
scrollLeft([val]):获取匹配元素相对滚动条左侧的偏移。
$(window).scrollTop() //获取值 $("div").scrollTop() //标签相对滚动条顶部的偏移 $(window).scrollTop(0) //设置值,回到页面顶部 同理还有scrollLeft
offset([coordinates]):获取匹配元素在当前视口的相对偏移。返回的对象包含两个整型属性:top 和 left,以像素计
$("div").offset() //获取偏移值 $("div").offset().left //获取left值 $("div").offset().top
$("div").offset({top:100,left:0}) //设置值
移动面板示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="border: 1px solid #ddd;width: 600px;position: absolute;"> <div id="title" style="background-color: black;height: 40px;"></div> <div style="height: 300px;"></div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $(function(){ $('#title').mouseover(function(){ //mouseover当鼠标指针位于元素上方时,会发生 mouseover 事件。 $(this).css('cursor','move'); //cursor为move,移到该标签变换为移动的样式标签 }).mousedown(function(e){ //当鼠标指针移动到元素上方,并按下鼠标按键时,会发生 mousedown 事件。 var _event = e || window.event; var ord_x = _event.clientX; //获取鼠标当前相对于网页的位置 var ord_y = _event.clientY; var parent_left = $(this).parent().offset().left; //获取最外面div标签的偏移量 var parent_top = $(this).parent().offset().top; $(this).bind('mousemove', function(e){ //当鼠标指针在指定的元素中移动时,就会发生 mousemove 事件。 var _new_event = e || window.event; var new_x = _new_event.clientX; //获取新的鼠标所在位置 var new_y = _new_event.clientY; var x = parent_left + (new_x - ord_x); //计算div所要移动的值 var y = parent_top + (new_y - ord_y); $(this).parent().css('left',x+'px'); $(this).parent().css('top',y+'px'); }) }).mouseup(function(){ //当在元素上放松鼠标按钮时,会发生 mouseup 事件。 $(this).unbind('mousemove'); }); }) // $('#title').mouseover(function(){ //mouseover当鼠标指针位于元素上方时,会发生 mouseover 事件。 // $(this).css('cursor','move')}); //cursor为move,移到该标签变换为移动的样式标签 </script> </body> </html>
position():获取匹配元素相对父元素的偏移。返回的对象包含两个整型属性:top 和 left。
$("#i1").position() Object {top: 0, left: 260}
3、高度
height([val|fn]) :取得匹配元素当前计算的高度值(px)。
width([val|fn]):取得第一个匹配元素当前计算的宽度值(px)。
innerHeight():获取第一个匹配元素内部区域高度(包括补白、不包括边框)。
innerWidth():获取第一个匹配元素内部区域宽度(包括补白、不包括边框)。
outerHeight([options]):获取第一个匹配元素外部高度(默认包括补白和边框)。
outerWidth([options]):获取第一个匹配元素外部宽度(默认包括补白和边框)。
html文件: <div style="width: 300px;height: 100px;border: 1px solid red;padding: 2px;"> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> $("div").height() #纯高度 100 $("div").width() #纯宽度 300 $("div").innerHeight() #纯高度+ padding(补白) 104 $("div").innerWidth() #纯宽度+ padding(补白) 304 $("div").outerHeight() #纯高度度+ padding(补白)+border(边框) 106 $("div").outerHeight() #纯宽度+ padding(补白)+border(边框) 106
六、事件
jQuery绑定事件的几种方式:
$(".c1").click()
$(".c1").bind('click',function(){}) //3.0+已弃用,官方解释建议用on
$(".c1").unbind('click',function(){})
$(".c1").on('click',function(){})
$(".c1").off('click',function(){})
$(".c1").delegate('a','click',function(){}) //3.0+已弃用,使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。
$(".c1").undelegate('a','click',function(){})
阻止事件发生
return false 阻止事件发生
先来回顾下html中的a标签,如果a标签指定href,我们点击a标签就会跳转到相应的网址,这个就相当于一次事件的发生
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a onclick="return ClickOn()" href="http://www.baidu.com">走你</a> <!--以DOM的方式阻止事件,需要加return--> <a id="i1" href="http://www.baidu.com">走你</a> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> function ClickOn() { alert(123); // return false //阻止事件 return true } $("#i1").click(function () { alert(456); return false }) </script> </body> </html>
一个简单的表单验证
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .error{ color: red; } </style> </head> <body> <form action="s61.html" method="post"> <div><span style="display: inline-block;width: 60px;padding-bottom: 10px">用户名</span> <input type="text"></div> <div><span style="display: inline-block;width: 60px;padding-bottom: 10px">密码</span> <input type="password"></div> <div><input type="submit" value="提交"></div> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $("input[type='submit']").click(function () { var tag = true; $(".error").remove(); //这里是实现一个当输入不为空时,删除此标签 $("input[type='text'],input[type='password']").each(function () { var val = $(this).val(); console.log(val.trim()); if (val.length <=0){ span_tag = document.createElement("span"); $(span_tag).text("必填"); $(span_tag).addClass("error"); $(this).after(span_tag); tag=false } }); return tag; }) </script> </body> </html>
页面框架加载后自动执行
(
function
(arg){
console.log(arg);
})(
'123'
)
//当页面框架加载完毕后,自动执行,像我们之前的都是当页面所有元素完全加载完毕后执行
实际应用中,我们一般都用这种方法
(
function
(arg){
console.log(arg);
})(
'123'
)
七:jquery扩展以及自执行函数的应用
jquery扩展
第一种扩展方式:jQuery.extend(object) 扩展jQuery对象本身。jQuery可以用$代替
jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); jQuery.min(2,3); // => 2 jQuery.max(4,5); // => 5
第二种扩展方式:jQuery.fn.extend(object) //扩展 jQuery 元素集来提供新的方法(通常用来制作插件)。jQuery可以用$代替
jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } }); $("input[type=checkbox]").check(); //调用方式与之前有区别,这个一定要用选择器的方式来调用 $("input[type=radio]").uncheck();
在我们引用插件的时候,可能会出现全局变量的冲突,这里就要用到自执行函数
(function(jQuery){ jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } }); })(jQuery)
Ajax
页面重载location.reload()
$.ajax( { url:"路径", type:"类型" POST、GET等 data:{'user':root} 发送给服务器的数据 success:function(data){} 成功后执行的函数,data为返回的数据 })
建议永远让服务器端返回一个字典
return HttpResponse(json.dumps(字典))
form表单中的数据打包发送给服务器 $.ajax( { url:$("#id").serialize() type:"类型" POST、GET等 data:{'user':root} 发送给服务器的数据 success:function(data){} 成功后执行的函数,data为返回的数据 })