2025年『jQuery 使用手册』

『jQuery 使用手册』一 jQuery 入门 1 介绍 jQuery 是一个轻量级的 写的少 做的多 的 JavaScript 库 简化了 javascript 的操作 例如 AJAX 调用 和 DOM 操作 等 jQuery 官网 https jquery com jQuery 插件库

大家好,我是讯享网,很高兴认识大家。

一、jQuery 入门

(1)介绍

jQuery 是一个轻量级的 “写的少,做的多” 的 JavaScript 库。

简化了 javascript 的操作,例如 AJAX调用 和 DOM操作 等……

jQuery 官网:https://jquery.com
jQuery 插件库:http://www.jq22.com
jQuery 之家:http://www.htmleaf.com

(2)使用模板

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script> <script> $(function () { 
      }); </script> 

讯享网

其中,$ 是 jQuery 的别称,同时也是 jQuery 的顶级对象。

(3)DOM 和 jQuery 对象转换

讯享网<video src="mov.mp4" muted></video> <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script> <script> // 🔘原生JS方法 let videoDOM = document.querySelector("video"); videoDOM.play(); // $('video').play() // ❌ jQuery 里面没有 play 这个方法 // 解决:将 jQuery对象 转换为 DOM对象 // ✅方法一 $("video")[0].play(); // ✅方法二 $("video").get(0).play(); </script> 

二、jQuery 常用API

1、选择器

选择器:

$(".nav") $("ul li") $("[href='#']") $("[href!='#']") $("[href$='.jpg']") 

筛选选择器:

讯享网$("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"); // 偶数 

筛选方法:

$(".son").parent() // 返回的是 最近一级的父级元素 $(".nav").children("p").css("color", "red"); // 类似 ul>li $(".nav").find("p").css("color", "red"); // 类似 ul li $("ol .item").siblings("li").css("color", "red"); // 除了自身元素之外的所有亲兄弟 $("ul li").eq(2).css("color", "blue"); // 指定索引值 $("div:first").hasClass("current") // 判断是否有某个类名 

2、样式操作

css 方法:

讯享网$("div").css("width", "300px"); // 写法一 $("div").css("width", 300); // 写法二 // 复合属性:驼峰命名,对象方式 $("div").css({ 
    width: 400, height: 400, backgroundColor: "red" }) 

类操作:

// 1. 添加类 addClass() $('div').addClass("current"); // 2. 删除类 removeClass() $('div').removeClass("current"); // 3. 切换类 toggleClass() $('div').toggleClass("current"); 

案例:tab栏切换

讯享网$(".tab_list li").click(function () { 
    // tab标题切换 $(this).addClass("current").siblings().removeClass("current"); // tab内容切换 var index = $(this).index(); $(".tab_con .item").eq(index).show().siblings().hide(); }); 

3、效果

【括号传参共通点: 第一个参数是持续时间,第二个参数是回调函数(皆为可选)】

显示/隐藏:

$("div").show() $("div").hide() $("div").toggle() 

滑动:

讯享网$("div").slideDown(); $("div").slideUp(); $("div").slideToggle(); 

淡入淡出:

$("div").fadeIn(1000); $("div").fadeOut(1000); $("div").fadeToggle(1000); // fadeTo() : 修改透明度,速度和透明度必写! $("div").fadeTo(1000, 0.5); 

停止动画排队:

讯享网// stop 方法必须写到动画的前面 $('div').children("ul").stop().slideToggle(3000); 

自定义动画:

$("div").animate({ 
    width: 500 }, 500); 

4、属性操作

讯享网// 获取元素固有的属性值 console.log($("a").prop("href")); console.log($('input').prop("checked")); // 获取 input 复选框的 状态 console.log($("div").data("index")); // 获取 div 自定义属性 data-index 的值 // 设置元素固有的属性值 $("a").prop("title", "我们都挺好"); 

5、文本属性值

// 1. 获取设置元素内容 html() console.log($("div").html()); $("div").html("123"); // 设置 // 2. 获取设置元素文本内容 text() console.log($("div").text()); $("div").text("123"); // 设置 // 3. 获取设置表单值 val() console.log($("input").val()); $("input").val("123"); // 设置 

6、元素操作

返回指定祖先元素:

讯享网console.log($(".four").parent().parent().parent()); console.log($(".four").parents()); // 也包括了 body 和 html console.log($(".four").parents(".one")); 

遍历元素:

let colorArr = ["red", "green", "blue"]; let sum = 0; // $.each("jQuery对象/dom对象/数组", function (index, domEle) {}) // $("jQuery对象/dom对象/数组").each(function(){}) $.each($("div"), function (index, domEle) { 
    $(domEle).css("color", colorArr[index]); sum += parseInt($(domEle).text()); }); console.log(sum); 

创建添加删除元素:


讯享网

讯享网/* 1、创建元素 */ let newLi = $("<li>创建的li</li>"); let newDiv = $("<div>我是后妈生的</div>"); /* 2、添加元素 */ // 内部添加 $("ul").append(newLi); // 塞最后面 $("ul").prepend(newLi); // 塞最前面 // 外部添加 $(".test").before(newDiv); /* 3、删除元素 */ $("ul").remove(); // 自我删除 $('ul').empty() // 删除自己的所有子节点 $("ul").html(""); // 等同于 empty() 

7、尺寸、位置操作

元素大小:

// 1. width():获取设置元素 width和height大小 console.log($("div").width()); // 2. innerWidth():获取设置元素 width和height + padding 大小 console.log($("div").innerWidth()); // 3. outerWidth():获取设置元素 width和height + padding + border 大小 console.log($("div").outerWidth()); // 4. outerWidth(true):获取设置 width和height + padding + border + margin console.log($("div").outerWidth(true)); // height 的获取也类似上面的方法 

元素位置:

讯享网.father { 
    position: relative; margin: 100px; /* 此处省略 宽高 */ } .son { 
    position: absolute; left: 10px; top: 10px; /* 此处省略 宽高 */ } 
// 1、offset():获取设置距离文档的位置(偏移) console.log($(".son").offset()); // {"top": 110,"left": 110} // 2、position():获取距离带有定位父级位置(偏移),如果没有带有定位的父级,则以文档为准 // 这个方法只能获取不能设置偏移 console.log($(".son").position()); // {"top": 10,"left": 10} 

被卷去的头部:

讯享网// scrollTop():被卷去的头部 // scrollLeft():被卷去的左侧 $(document).scrollTop(100); // 页面滚动事件 let boxTop = $(".container").offset().top; // 距离文档的距离 $(window).scroll(function () { 
    console.log($(document).scrollTop()); if ($(document).scrollTop() >= boxTop) { 
    $(".back").fadeIn(); } else { 
    $(".back").fadeOut(); } }); // 返回顶部 $(".back").click(function () { 
    // 太生硬了,加点动画会更合适点 // $(document).scrollTop(0); // 动画优化:❗不能是文档而是html和body做动画 $("body,html").stop().animate({ 
    scrollTop: 0 }); }); 

8、事件

事件注册:

/* 1. 单个事件注册 */ $("div").click(function() { 
    $(this).css("background", "purple"); }); /* 2. 事件处理on */ // (1) on可以绑定1个或者多个事件处理程序 $("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"); }); // (2) on可以实现事件委托(委派) // click 是绑定在ul 身上的,但是 触发的对象是 ul 里面的小li $("ul").on("click", "li", function() { 
    alert(11); }); // (3) on可以给未来动态创建的元素绑定事件 $("ol").on("click", "li", function() { 
    alert(11); }) var li = $("<li>我是后来创建的</li>"); $("ol").append(li); 

事件解绑:

讯享网// 1. 事件解绑 off  $("div").off(); // 这个是解除了div身上的所有事件 $("div").off("click"); // 这个是解除了div身上的点击事件 $("ul").off("click", "li"); // 2. one() 但是它只能触发事件一次 $("p").one("click", function() { 
    alert(11); }) 

自动触发事件:

// 1.元素.事件() $("div").click(); // 会触发元素的默认行为 // 2.元素.trigger("事件") $("div").trigger("click"); // 会触发元素的默认行为 $("input").trigger("focus"); // 3.元素.triggerHandler("事件") 就是不会触发元素的默认行为 $("div").triggerHandler("click"); $("input").on("focus", function() { 
    $(this).val("你好吗"); }); $("input").triggerHandler("focus"); 

事件对象:

讯享网$("div").on("click", function(event) { 
    event.stopPropagation(); }) 

拷贝对象:$.extend([deep], targetObj, obj);

var targetObj = { 
   }; var obj = { 
    id: 1 }; $.extend(targetObj, obj); // 默认为 false 浅拷贝 $.extend(true, targetObj, obj); // 深拷贝 

9、Ajax

讯享网$.ajax({ 
    type: "get", // 请求方式 url: "url", // 请求路径 dataType: "json", // 预期返回一个 json 类型数据 success: function (data) { 
    console.log(data); // data是形参名,代表返回的数据 }, }); 

10、插件推荐

(1)瀑布流 (waterfall.js)

网址:http://www.htmleaf.com/jQuery/pubuliuchajian/201601093003.html

具体使用:

<link rel="stylesheet" href="css/normalize.css" /> <link rel="stylesheet" type="text/css" href="css/default.css" /> <style> #gallery-wrapper { 
      position: relative; max-width: 75%; width: 75%; margin: 50px auto; } img.thumb { 
      width: 100%; max-width: 100%; height: auto; } .white-panel { 
      position: absolute; background: white; border-radius: 5px; box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.3); padding: 10px; } .white-panel:hover { 
      box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5); margin-top: -5px; -webkit-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; cursor: pointer; } </style> <section id="gallery-wrapper"> <article class="white-panel"> <img src="images/P_000.jpg" class="thumb" /> </article> .... </section> <script src="js/jquery-1.11.0.min.js"></script> <script src="js/pinterest_grid.js"></script> <script> $(function () { 
      $("#gallery-wrapper").pinterest_grid({ 
      no_columns: 4, padding_x: 10, padding_y: 10, margin_bottom: 50, single_column_breakpoint: 700, }); }); </script> 

(2)图片懒加载 (EasyLazyload.js)

网址:https://www.jq22.com/jquery-info11629

具体使用:

讯享网<style> img { 
      display: block; margin: 0 auto; margin-top: 100px; } </style> <img data-lazy-src="images/P_000.jpg" /> .... <script src="js/jquery.min.js"></script> <script src="js/EasyLazyload.min.js"></script> <script> lazyLoadInit({ 
      showTime: 1100, onLoadBackEnd: function (i, e) { 
      console.log("onLoadBackEnd:" + i); }, onLoadBackStart: function (i, e) { 
      console.log("onLoadBackStart:" + i); }, }); </script> 

(3)全屏滚动 (fullpage.js)

具体使用:

<link rel="stylesheet" href="css/fullpage.min.css" /> <style> #fp-nav ul li a.active span, #fp-nav ul li a span { 
      background-color: red !important; } .section1 { 
      background: url(http://idowebok.u.qiniudn.com/77/1.jpg) 50%; } .section2 { 
      background: url(http://idowebok.u.qiniudn.com/77/2.jpg) 50%; } .section3 { 
      background: url(http://idowebok.u.qiniudn.com/77/3.jpg) 50%; } .section4 { 
      background: url(http://idowebok.u.qiniudn.com/77/4.jpg) 50%; } </style> <div id="dowebok"> <div class="section section1"> <h3>第一屏</h3> </div> <div class="section section2"> <h3>第二屏</h3> </div> <div class="section section3"> <h3>第三屏</h3> </div> <div class="section section4"> <h3>第四屏</h3> </div> </div> <script src="js/jquery.min.js"></script> <script src="js/fullpage.min.js"></script> <script> $(function () { 
      $("#dowebok").fullpage({ 
      sectionsColor: ["pink", "#4BBFC3", "#7BAABE", "#f90"], navigation: true, }); }); </script> 

(4)bootstrap 框架

bootstrap 框架也是依赖于 jQuery 开发的,因此里面的 js插件使用 ,也必须引入jQuery 文件。


三、相关案例

(1)高亮显示

高亮显示

讯享网$(function () { 
    $(".wrap li").hover( // 鼠标悬停:其它li透明度变为0.5 function () { 
    $(this).siblings().stop().fadeTo(400, 0.5); }, // 鼠标离开:其它li透明度恢复原样 function () { 
    $(this).siblings().stop().fadeTo(400, 1); } ); }); 

(2)手风琴

手风琴

$(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(); }); }); 

(3)购物车

讯享网$(function () { 
    // 全选 $(".checkall").change(function () { 
    // 添加复选框点击状态 $(".j-checkbox, .checkall").prop("checked", $(this).prop("checked")); // 选中的项就添加背景色 if ($(this).prop("checked")) { 
    $(".cart-item").addClass("check-cart-item"); } else { 
    $(".cart-item").removeClass("check-cart-item"); } }); // 单选 $(".j-checkbox").change(function () { 
    // 如果 选中的复选框个数 和 复选框总个数 一致,则让全选为选中状态 if ($(".j-checkbox:checked").length === $(".j-checkbox").length) { 
    $(".checkall").prop("checked", true); } else { 
    $(".checkall").prop("checked", false); } // 选中的项就添加背景色 if ($(this).prop("checked")) { 
    $(this).parents(".cart-item").addClass("check-cart-item"); } else { 
    $(this).parents(".cart-item").removeClass("check-cart-item"); } }); // + $(".increment").click(function () { 
    // 获取现有的数量 let num = $(this).siblings(".itxt").val(); // +1 num++ // 赋值回填 $(this).siblings(".itxt").val(num) // 单价 let singleP = $(this).parents('.p-num').siblings('.p-price').html().substr(1) // 计算新的小计总金额 let total = (singleP * num).toFixed(2) // 赋值回填 $(this).parents('.p-num').siblings('.p-sum').html('¥'+ total) getSum(); // 重新计算 }); // - $(".decrement").click(function () { 
    // 获取现有的数量 let num = $(this).siblings(".itxt").val(); // -1 if(num === 1) return false num-- // 赋值回填 $(this).siblings(".itxt").val(num) // 单价 let singleP = $(this).parents('.p-num').siblings('.p-price').html().substr(1) // 计算新的小计总金额 let total = (singleP * num).toFixed(2) // 赋值回填 $(this).parents('.p-num').siblings('.p-sum').html('¥'+ total) getSum(); // 重新计算 }); // 手动改变数量框 $('.itxt').change(function(){ 
    let num = $(this).val() let p = $(this).parents('.p-num').siblings('.p-price').html().substr(1) $(this).parents('.p-num').siblings('.p-sum').html('¥'+ (p * num).toFixed(2)) getSum(); // 重新计算 }) getSum(); // 一进入页面就计算 // 计算总数 function getSum() { 
    let count = 0; let money = 0; // 计算总数量 $(".itxt").each(function (i, ele) { 
    count += parseInt($(ele).val()); }); $(".amount-sum em").text(count); // 计算总价格 $(".p-sum").each(function (i, ele) { 
    money += parseFloat($(ele).text().substr(1)); }); $(".price-sum em").text("¥" + money.toFixed(2)); } // 单机删除 $('.p-action a').click(function(){ 
    $(this).parents('.cart-item').remove() getSum(); // 重新计算 }) // 删除选中 $('.remove-batch').click(function(){ 
    $('.j-checkbox:checked').parents('.cart-item').remove() getSum(); // 重新计算 }) // 清空购物车 $('.clear-all').click(function(){ 
    $('.cart-item').remove() getSum() // 重新计算 }) }); 

(4)电梯导航

$(function(){ 
    // 节流阀 let flag = true; // 获取需要显示 电梯导航 的盒子位置 let toolTop = $(".recommend").offset().top; // 首次加载页面,隐藏 电梯导航 toggleTool(); // 显示/隐藏 电梯导航 function toggleTool() { 
    if ($(document).scrollTop() >= toolTop) { 
    $(".fixedtool").fadeIn(); } else { 
    $(".fixedtool").fadeOut(); } } $(window).scroll(function () { 
    // 监测 电梯导航 的 显示/隐藏 toggleTool(); // 页面滚动的过程,给对应的电梯导航li 添加高亮 // 思路:遍历每个楼层的距离文档高度,做出判断添加 if (flag) { 
    $(".floor .w").each(function (i, ele) { 
    if ($(document).scrollTop() >= $(ele).offset().top) { 
    $(".fixedtool li").eq(i).addClass("current").siblings().removeClass(); } }); } }); $(".fixedtool li").click(function () { 
    flag = false; // 获取点击了具体项的索引值 let index = $(this).index(); // 获取点击项的距离文档位置的大小 let distance = $(".floor .w").eq(index).offset().top; // 最后,实现位置跳转(❗这里同时也触发了上面的滚动事件,造成Bug,用到节流阀的知识) $("body,html") .stop() .animate({ 
    scrollTop: distance }, function () { 
    flag = true; }); // 同时,自身的高亮也要切换显示 $(this).addClass("current").siblings().removeClass(); }); }) 

(5)微博发布

讯享网// 1.点击发布按钮 $(".btn").on("click", function() { 
    // 新增标签 var li = $("<li></li>"); li.html($(".txt").val() + "<a href='javascript:;'> 删除</a>"); $("ul").prepend(li); // 添加动作 li.slideDown(); // 下拉添加效果 $(".txt").val(""); // 清空输入框内容 }) // 2.点击的删除按钮 // $("ul a").click(function() { // ❌此时的click不能给动态创建的a添加事件 // alert(11); // }) // on可以给动态创建的元素绑定事件 $("ul").on("click", "a", function() { 
    $(this).parent().slideUp(function() { 
    $(this).remove(); }); }) 

(6)toDoList

toDoList

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; } } 
讯享网<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"> <!-- <li><input type="checkbox"><p>123</p><a href="javascript:;" id=""></a></li> --> </ol> <h2>已经完成 <span id="donecount"></span></h2> <ul id="donelist"> <!-- <li><input type="checkbox" checked><p>123</p><a href="javascript:;" id=""></a></li> --> </ul> </section> <footer>Copyright &copy; 2023 todolist.cn</footer> 
$(function () { 
    // 一开始就渲染数据结构 load() // 1. 按下回车 把完整数据 存储到本地存储里面 $("#title").on("keydown", function (event) { 
    if (event.keyCode === 13) { 
    if (!$(this).val()) { 
    alert("请输入您要的操作"); } else { 
    let originalData = getData(); originalData.push({ 
    title: $(this).val(), done: false, }); saveData(originalData); load() $(this).val('') } } }); // 3. toDoList 删除操作 $('ol,ul').on('click', 'a', function(){ 
    let data = getData() let index = $(this).attr('id') data.splice(index, 1) saveData(data) load() }) // 4. toDoList 正在进行和已完成选项操作 $('ol,ul').on('change', 'input', function(){ 
    let data = getData() let index = $(this).siblings('a').attr('id') // 同步数据到本地 data[index].done = $(this).prop('checked') saveData(data) load() }) // 获取本地数据 function getData() { 
    let data = localStorage.getItem("todolist"); if (data !== null) { 
    return JSON.parse(data); } else { 
    return []; } } // 保存数据到本地 function saveData(data) { 
    localStorage.setItem("todolist", JSON.stringify(data)); } // 渲染加载数据 function load(){ 
    let data = getData() let todoCount = 0 let doneCount = 0 $('ol,ul').empty() $.each(data, function(i, n){ 
    if(!n.done){ 
    $('ol').prepend('<li><input type="checkbox"><p>' + n.title + '</p><a href="javascript:;" id="' + i + '"></a></li>') todoCount++ } else{ 
    $('ul').prepend('<li><input type="checkbox" checked><p>' + n.title + '</p><a href="javascript:;" id="' + i + '"></a></li>') doneCount++ } }) $('#todocount').text(todoCount) $('#doneCount').text(doneCount) } }); 
小讯
上一篇 2025-02-19 13:51
下一篇 2025-01-10 16:17

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/94181.html