前端之jQuery
目录
-简介
--本质
jQuery本质就是js代码,只不过对其进行了封装使使用起来更方便,且内部添加了更多功能
类似于Python的模块,只不过在前端称为“类库”
下载链接:jQuery官网
中文文档:jQuery AP中文文档
--介绍
- jQuery是一个轻量级的、兼容多浏览器的JavaScript库
- jQuery使用户方便的处理HTML、Document、Events、实现动画效果,方便地进行Ajax交互,极大化地简化JavaScript编程。它的宗旨就是“Write less, Do more.”
--优势
- 一款轻量级的js框架,jQuery核心js文件才几十kb,不影响页面加载速度
- 丰富的DOM选择器,用起来方便
- 链式表达式。jQuery的链式操作可以把多个操作写在一行代码里,更加简洁
- 可读性比js强。事件、动画、样式支持
- Ajax操作支持。jQuery简化了Ajax操作,后端只需返回一个JSON格式数据即可与前端通信
- 跨浏览器兼容。jQuery基本兼容了所有现在主流的浏览器
- 插件扩展开发。jQuery有丰富的第三方插件,如树形菜单、日期控件。支持三方改写封装
--基本使用
---导入方式
1、进入官网下载文件到本地,使用时导入即可jQuery
2、引入jQuery的CDN(内容分发网络)服务
前端免费CDN网站:bootcdn
<script src="htttps://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
---基本语法
jQuery(选择器).操作()
秉持jQuery的宗旨,以后写jQuery都和用$代替: $(选择器).操作()
-选择器
--基本选择器
- id: $('#id')
- class: $('.class')
- 标签: $('标签')
注:选择器返回的都是jQuery对象(即数组,不过在jQuery中叫jQuery对象),通过索引取标签对象
--组合选择器
后代$('div p') 儿子$('div>p') 邻居$('div+p') 弟弟$('div~p')
--属性选择器
$('[username]') $('[type='text']') $('p[name='weer']')
--分组与嵌套
分组$('#d1, .c1') 嵌套$('div.#d1'):找为d1的div
-筛选器
--基本筛选器
$('ul li:first') ul里面的大儿子li $('ul li:last') ul里面的小儿子li $('ul li:eq(2)') ul对象后代li对象数组的索引为2的标签 $('ul li:even') li的jQuery对象里的索引为偶数的标签数组 $('ul li:odd') li的jQuery对象里的索引为奇数的标签数组 $('ul li:gt(2)') 索引大于2的 $('ul li:not(#d1)') 除了id为d1的 $('div:has(p)') 内部含有p标签的div都选
注:以上都可以把方法拿到外面加点调用,比如$('div span:first')<==>$('div span').first()
--表单筛选器
只针对表单标签里的标签
$(':text') <==> $('input[type='text']') $(':password') <==> $('input[type='password']') $(':file') $(':radio') $(':checkbox') $(':submit') ......
也可针对表单属性进行筛选:
$(':disabled') $(':checked') $(':seclected')...
注: :checked会将checked和selected的都拿到
--筛选器方法
$('#d1').next() | 下一个 | $('#d1').parent() | 父标签 |
$('#d1').nextAll() | 下一个所有 | $('#d1').parent().parent() |
父的父,可多次 html的父为document对象 再上就没有了 |
$('#d1').nextUntil('.c1') | 下一个所有直到不包含 | $('#d1').parents() | 父的所有 |
$('#d1').prev() | 上一个 | $('#d1').parentsUntil('body') | 父的所有直到不包含 |
$('#d1').prevAll() | 上一个所有 | $('#d1').children() | 儿子们 |
$('#d1').prevUntil('.c1') | 上一个所有直到不包含 | $('#d1').siblings() | 兄弟们 |
-操作
--类操作
.addClass()
.removeClass()
.hasClass()
.toggleClass()
--css操作
--位置操作
.offset() 相对于浏览器窗口的距离 .position() 相对于父标签的距离 .scrollTop() 滚轮滑动导致距浏览器上端距离 $(window).scrollTop() 显示向上翻了多少像素 $(window).scrollTop(500) 自动跳转到向上滚了500像素去 .scrollLeft() 滚轮左右滑动导致左右偏移距离
--尺寸操作
---p标签内部文本--- $('p').height() $('p').width() ---文本+padding--- $('p').innerHeight() $('p').innerWidth() ---文本+padding+border--- $('p').outerHeight() $('p').outerWidth()
--文本操作
原生js jQuery
.innerText .text()
.innerHtml .html()
--获取值操作
.val() # 不加参数即为获取值,加参数即为设置值
获取文件:jQuery对象转js对象
$(':file').files[0]
--属性操作
js jQuery
setAttribute() attr(name,value)
getAttribute() attr(name)
removeAttribute() removeAttr(name)
注:对一些用户选择标签checkbox、radio、option等,可用prop()判断用户是否选择
--标签操作
js jQuery createElement('p') $('<p>') appendChild() append() eg: let $pEle = $('<p>'); $pEle.text('weer') $('#d1').append($pEle) // 内部尾部追加 $('#d1').prepend($pEle) // 内部头部追加 $('#d1').after($pEle) // 放在同级后面 $('#d1').before($pEle) // 放在同级前面 .remove() 移除所有 .empty() 只清空内容
-事件
--绑定方式
1、$(' ').click(function(){}) 2、$(' ').on('click',function(){})
常用事件:
click
hover
blur
focus
change
keyup
--示例
---克隆事件
<style> body{margin: 0;} #d1{ background-color: orange; height: 200px; width: 200px; top: 0; left: 0; } </style> <body> <button id="d1">点击就送屠龙宝刀!</button> <script> $("#d1").on('click', function (){ // $(this).clone().insertAfter('body') // clone默认克隆html和css,不会克隆绑定事件 $(this).clone(true).insertAfter('body') // 括号内加true即可克隆绑定事件 }) </script> </body>
---模态框显示
<style> body{margin:0;} #cover{ background-color: rgba(0,0,0,0.5);top: 0;left: 0;bottom: 0;right: 0; position:fixed;z-index: 99; } #modal{ background-color: white;position: fixed;left: 40%;top: 20%; width: 400px;height: 400px;z-index: 100; } .hide{display: none;} </style> <body> <div> <p>这是底层</p> <button id="login">登录</button> </div> <div id="cover" class="hide"></div> <div id="modal" class="hide"> <h2>登录</h2> <p>username:<input type="text"></p> <p>password:<input type="password"></p> <input type="submit" id="submit"> </div> <script> $('#login').click(function (){ $('#cover,#modal').removeClass('hide') }) $('#submit').click(function (){ $('#cover,#modal').addClass('hide') }) </script> </body>
---对应菜单栏显示
点击某个菜单就显示该菜单下的内容,其余隐藏
<style> body{margin: 0;} #left{ width: 20%;height: 100%;position: fixed;background-color: #4e4e4e;text-align: center; } .title{font-size: 24px;color: white;} .item{border: 1px solid black;font-size: 16px;} .hide{display: none;} </style> <body> <div id="left"> <div class="title">menu 1 <div class="item hide">111</div> <div class="item hide">222</div> <div class="item hide">333</div> </div> <div class="title">menu 2 <div class="item hide">www</div> <div class="item hide">mmm</div> <div class="item hide">qqq</div> </div> <div class="title">menu 3 <div class="item hide">aaa</div> <div class="item hide">bbb</div> <div class="item hide">ccc</div> </div> </div> <script> $('.title').click(function (){ $(this).children().toggleClass('hide') }) </script> </body>
---返回顶部
<style> body{margin: 0;} #backTop{width: 50px;height: 50px;bottom: 10px;right: 20px; position: fixed;} .hide{display: none;} </style> <body> <div style="background-color: red;width: 100%;height: 800px;"></div> <div style="background-color: green;width: 100%;height: 800px;"></div> <div style="background-color: purple;width: 100%;height: 800px;"></div> <button id="backTop" class="hide">回到顶部</button> <script> $('#backTop').click(function (){ $(window).scrollTop(0) }) $(window).scroll(function (){ if($(window).scrollTop() > 600){ $('#backTop').removeClass('hide') }else { $('#backTop').addClass('hide') } }) </script> </body>
---自定义登录校验
<body> <p>username: <input type="text" id="name"> <span style="color: red;"></span> </p> <p>password: <input type="password" id="pwd"> <span style="color: red;"></span> </p> <input type="submit" id="submit"> <script> $('#submit').click(function (){ if(!$('#name').val()){$('#name').next().text('用户名不能为空')} if(!$('#pwd').val()){$('#pwd').next().text('密码不能为空')} }) $(':input').focus(function (){ $(this).next().text('') }) </script> </body>
---键盘按下操作
<script> $(window).keydown(function (event){ //event用于获取按键 alert(event.keyCode); // 每个按键其实是有个编码来对应 if(event.keyCode == 16){alert('你点击了shift键')} // shift编码是16 }) </script>
--阻止后续事件执行
<script> $(':input').on('click', function (enent){ $('p').text('点击提交后给我添加的文字') /* 此时点击提交理应在p中显示上述文字 但由于submit点击后自动触发刷新事件 所以文字不会显示出来 */ // 阻止标签后续执行的方式一! return false // 阻止标签后续事件执行的方式二 event.preventDefault() }) </script>
--防止冒泡
冒泡就是对嵌套标签,触发子代标签事件而父代也触发,连环
<body> <div id="d1">div <p id="d2">div>p <span id="d3">div>p>span</span> </p> </div> <script> $('#d1').click(function (){alert('div')}) $('#d2').click(function (){alert('div>p')}) // 点击p标签中的文字会alert两次 // $('#d3').click(function (){alert('div>p>span')}) // 点击span中文字会alert三次 $('#d3').click(function (event){ alert('div>p>span') // 消除冒泡的方式一 return false // 消除冒泡的方式二 event.stopPropagation() // 此时点击span中文字只会alert自己的一次了 }) </script> </body>
--事件委托
在指定范围内把事件委托给某个标签来做,无论原先的还是动态添加的
主要用来针对后面动态添加的方法也能有原先绑定的事件
<body> <button class="c1">你过来啊!</button> <!-- <script> --> <!-- $('button').click(function (){alert('我就过来了!')}) --> <!-- //原生button标签点击可触发alert事件,但若在控制台或后台人为动态添加button到body内,点击新动态添加的不会触发alert事件 --> <!-- </script> --> <script> $('body').on('click','c1',function (){alert('我就过来了!')}) // 含义是所有在body范围内的含c1的标签(不管原生还是动态添加的)点击后都能触发alert事件 </script> </body>
--简单动画效果
<div style="background-color:red;height:600px;width:400px"></div> $('div').hide(4000) 未消失才4s隐藏 $('div').show(4000) 未出现4s后出现 $('div').toggle(4000) 有则消失,无则出现 $('div').fadeIn(4000) 消失才渐变出现 $('div').fadeOut(4000) 出现才渐变消失 $('div').fadeTo(4000, 0.5) 渐变到透明度为0.5结束 $('div').fadeToggle(4000) 有则渐变消失,无则渐变出现 $('div').slideUp(4000) 上翻消失 $('div').slideDown(4000) 下翻出现
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <script src="/static/js/jQuery%203.6.0.js"></script> <title>点赞动画示例</title> <style> div { position: relative; display: inline-block; } div>i { display: inline-block; color: red; position: absolute; right: -16px; top: -5px; opacity: 1; } </style> </head> <body> <div id="d1">点赞</div> <script> $("#d1").on("click", function () { var newI = document.createElement("i"); newI.innerText = "+1"; $(this).append(newI); $(this).children("i").animate({ opacity: 0 }, 1000) }) </script> </body> </html>
-- .each()方法
相当于for循环,更简单的循环迭代器
- 可对jQuery对象遍历迭代,传一个参数是索引,传两个参数是索引+jQuery对象
<div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <script> $('div').each(function(index){console.log(index)}); $('div').each(function(index, obj){console.log(index, obj)}); </script>
- $.each([111,222,333], function(index, obj){console.log(index, obj)});
-- .data()方法
让标签帮我们存数据,且用户右键检查看不到!
$('div').data(key,value); // 所有div标签保存一个名为key值为value $('div').data(key); // 返回第一个div标签你中保存的key值对应的value $('div').removeData(key); // 移除元素上存放key对应的数据,不加key值表示移除所有保存的数据
-插件(了解)
jQuery.extend(object)
jQuery的命名空间下添加新的功能。多用于插件开发者向 jQuery 中添加新函数时使用。
<script> 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 </script>
jQuery.fn.extend(object)
一个对象的内容合并到jQuery的原型,以提供新的jQuery实例方法。
<script> jQuery.fn.extend({ check:function(){ return this.each(function(){this.checked =true;}); }, uncheck:function(){ return this.each(function(){this.checked =false;}); } }); // jQuery对象可以使用新添加的check()方法了。 $("input[type='checkbox']").check(); </script>
单独写在文件中的扩展:
(function(jq){
jq.extend({
funcName:function(){
...
},
});
})(jQuery);
示例:
自定义的jQuery登录验证插件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录校验示例</title> <style> .login-form { margin: 100px auto 0; max-width: 330px; } .login-form > div { margin: 15px 0; } .error { color: red; } </style> </head> <body> <div> <form action="" class="login-form" novalidate> <div> <label for="username">姓名</label> <input id="username" type="text" name="name" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="passwd">密码</label> <input id="passwd" type="password" name="password" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="mobile">手机</label> <input id="mobile" type="text" name="mobile" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="where">来自</label> <input id="where" type="text" name="where" autocomplete="off"> <span class="error"></span> </div> <div> <input type="submit" value="登录"> </div> </form> </div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="validate.js"></script> <script> $.validate(); </script> </body> </html>
"use strict"; (function ($) { function check() { // 定义一个标志位,表示验证通过还是验证不通过 var flag = true; var errMsg; // 校验规则 $("form input[type!=':submit']").each(function () { var labelName = $(this).prev().text(); var inputName = $(this).attr("name"); var inputValue = $(this).val(); if ($(this).attr("required")) { // 如果是必填项 if (inputValue.length === 0) { // 值为空 errMsg = labelName + "不能为空"; $(this).next().text(errMsg); flag = false; return false; } // 如果是密码类型,我们就要判断密码的长度是否大于6位 if (inputName === "password") { // 除了上面判断为不为空还要判断密码长度是否大于6位 if (inputValue.length < 6) { errMsg = labelName + "必须大于6位"; $(this).next().text(errMsg); flag = false; return false; } } // 如果是手机类型,我们需要判断手机的格式是否正确 if (inputName === "mobile") { // 使用正则表达式校验inputValue是否为正确的手机号码 if (!/^1[345678]\d{9}$/.test(inputValue)) { // 不是有效的手机号码格式 errMsg = labelName + "格式不正确"; $(this).next().text(errMsg); flag = false; return false; } } } }); return flag; } function clearError(arg) { // 清空之前的错误提示 $(arg).next().text(""); } // 上面都是我定义的工具函数 $.extend({ validate: function () { $("form :submit").on("click", function () { return check(); }); $("form :input[type!='submit']").on("focus", function () { clearError(this); }); } }); })(jQuery);
-思维导图