一、jQuery概述
1.1 JavaScript库
JavaScript库:即library,是一个封装好的特定的集合(函数和方法)
常见的JavaScript库有:
- jQuery
- Prototype
- YUI
- Dojo
- Ext JS
- 移动端的zepto
1.2 jQuery概念
jQuery是一个快速、简洁的JavaScript库,倡导写更少的代码,做更多的事。
jQuery封装了JavaScript常用功能代码
1.3 jquery的优缺点
(1)优点
1.代码都函数化了,都是封装好的函数,简化了代码,加快了代码的执行速度
2.有强大的选择器,支持近乎所有的css选择器,还有另外还可以加入插件使其支持XPath选择器,甚至开发者自己编写的选择器也支持。
3.浏览器兼容性出色,兼容很多类型的浏览器,JQuery也同时修复了一些浏览器之间的的差异,使开发者在开发项目不用在建立浏览器兼容库
4.jQuery极大的简化ajax编程,提供了一种更加简洁,统一的编程方式
5.jQuery也是一个为事件处理特点设计的框架,提供了静态绑定事件和动态绑定事件,完善了事件的处理机制。
6.JQuery封装了大量常用的DOM操作,使开发者在编写DOM操作相关程序的时候能得心应手。JQuery也能轻松地完成各种原本非常复杂的操作
(2)缺点
1.不能向后兼容。每一个新版本不能兼容早期的版本。
2.插件兼容性也比较差,不能兼容早期的版本
3.插件容易冲突,绑定相同事件或selector的时候最为突出
4.jQuery核心代码库对动画和特效的支持相对较差
1.4 jQuery网址
官网:https://jquery.com/
各个版本下载:https://releases.jquery.com/
二、jQuery的基本使用
2.1 jQuery的入口函数
// $('div').hide();
// 1、等页面DOM加载完再执行js代码
$(document).ready(function() {
$('div').hide();
})
// 2、等页面DOM加载完再执行js代码
$(function() {
$('div').hide();
})
- 相当于原生js的DOMContentLoaded
- 不同于原生js的load事件(等页面文档、外部js文件、css文件、图片加载完毕才执行内部代码)
2.2 jQuery的顶级对象 $
① $ 是jQuery的别称
// 1、 $ 是jQuery的别称
$(function() {
alert(11);
});
jQuery(function() {
alert(22);
// $('div').hide();
jQuery('div').hide();
})
// 2、 $ 也是jQuery的顶级对象
② $ 也是jQuery的顶级对象
2.3 jQuery对象和DOM对象
①DOM对象: 用原生js获取过来的对象就是DOM对象
②jQuery对象:用jquery方式获取过来的对象就是jQuery对象
$('div'); // $('div');就是一个jQuery对象
- jQuery只能使用jQuery中的方法;DOM对象只能使用原生js中的属性和方法。不能混合使用。
③ jQuery对象和DOM对象可以相互转换
1.DOM对象转化为jQuery对象:$(DOM对象)
$(mydiv)
2.jQuery对象转换为DOM对象(两种方式)
$('div')[index] //index是索引号
$('div').get(index) //index是索引号
三、jQuery常用API
3.1 jQuery选择器
3.1.1 jQuery基本选择器
$("选择器") // 里面选择器直接写CSS选择器即可,记得加符号
名称 | 用法 | 描述 |
---|---|---|
id选择器 | $(“#id”) | 获取指定id元素,第一个 |
全选择器 | $(“*”) | 匹配所有元素 |
类选择器 | $(“.class”) | 获取同一类class的元素 |
标签选择器 | $(“div”) | 获取同一标签div的元素 |
并集选择器 | $(“div,p,li”) | 获取多个元素 |
交集选择器 | $(“li.current”) | 获取交集元素 |
子代选择器 | $(“ul>li”) | 只获取ul儿子元素li |
后代选择器 | $(“ul li”) | 获取ul的所有后代li |
3.1.2 隐式迭代
隐式迭代:遍历内部DOM元素(伪数组形式存储)的过程就叫做隐式迭代
3.1.3 筛选选择器
语法 | 用法 | 描述 |
---|---|---|
:first | $(“li:first”) | 获取第一个元素 |
:last | $(“li:last”) | 获取最后一个元素 |
:eq(index) | $(“li:eq(2)”) | 获取li元素中索引号为index的元素,index从0开始 |
:odd | $(“li:odd”) | 获取li元素中索引号为奇数的元素 |
:even | $(“li:even”) | 获取li元素中索引号为偶数的元素 |
3.1.4 jQuery筛选方法 (重点)
语法 | 用法 | 说明 |
---|---|---|
parent() | $(“li”).parent() | 查找父级 |
children(selector) | $(“ul”).children(“li”) | 相当于$(“ul>li”),最近一级(亲儿子) |
find(selector) | $(“ul”).find(“li”) | 相当于$(“ul li”),后代选择器 |
siblings(selector) | $(“.first”).siblings(“li”) | 查找兄弟节点,不包括自身 |
nextAll([expr]) | $(“.first”).nextAll() | 查找当前元素之后所有的同辈元素 |
prevtAll([expr]) | $(“.last”).prevtAll() | 查找当前元素之前所有的同辈元素 |
hasClass(class) | $(“div”).hasClass(“protected”) | 检查当前元素是否含有某个特定的类,如果有,则返回true |
eq(index) | $(“li”).eq(2) | 相当于$(“li:eq(2)”),index从0开始;推荐使用 |
parents() | $(“li”).parents() | 查找所有父级,括号里可以筛选指定父级 |
3.1.5 排他思想
<script>
$(function() {
$('button').click(function() {
$(this).css('background', 'red');
$(this).siblings('button').css('background', '');
})
})
</script>
3.1.6 链式编程
$(this).css('background', 'red').siblings().css('background', '');
3.1.7 案例
淘宝服饰案例
<script src="js/jquery.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
color: black;
font-size: 14px;
}
.wrapper {
margin-left: 300px;
margin-top: 200px;
}
.wrapper #left {
float: left;
}
.wrapper #left li {
list-style: none;
width: 50px;
height: 25px;
text-align: center;
border: 2px solid #e9d1d0;
border-bottom: 0;
line-height: 30px;
/* 背景渐变 */
background-image: linear-gradient(to top, #fcf1ed, #fbfdfb);
}
.wrapper #left li:last-child {
border-bottom: 2px solid #e9d1d0;
}
.wrapper #left li:hover {
background-image: linear-gradient(to top, #a81911, #f8371b);
}
.wrapper #content {
float: left;
overflow: hidden;
}
.wrapper #content div {
display: none;
}
.wrapper #content div:first-child {
display: block;
}
.wrapper #content img {
height: 244px;
border: 1px solid #e9d1d0;
border-left: 0px;
}
</style>
</head>
<body>
<div class="wrapper">
<ul id="left">
<li><a href="#">女靴</a></li>
<li><a href="#">雪地靴</a></li>
<li><a href="#">冬裙</a></li>
<li><a href="#">妮大衣</a></li>
<li><a href="#">毛衣</a></li>
<li><a href="#">棉服</a></li>
<li><a href="#">女裤</a></li>
<li><a href="#">羽绒服</a></li>
<li><a href="#">牛仔裤</a></li>
</ul>
<div id="content">
<div>
<a href="#"><img src="../images/女靴.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/雪地靴.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/冬裙.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/呢大衣.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/男毛衣.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/棉服.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/女裤.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/羽绒服.jpg" alt=""></a>
</div>
<div>
<a href="#"><img src="../images/牛仔裤.jpg" alt=""></a>
</div>
</div>
</div>
<script>
// // 获得左边的li元素
// var leftlis = $('#left>li')
// // 获得右边的div元素
// var rightdiv = $('#content>div')
// // 给左边的li添加点击事件
// leftlis.click(function() {
// // 干掉所有人 .index()获取当前索引号
// rightdiv.hide();
// var index = $(this).index();
// // 留下我自己
// rightdiv.eq(index).show();
// })
$('#left li').mouseenter(function() {
let index = $(this).index();
console.log(index);
$('#content div').eq(index).show();
$('#content div').eq(index).siblings().hide();
})
</script>
3.2 jQuery样式操作
3.2.1 操作css方法
①参数只写属性名吗,则返回属性值
$(this).css('color')
②参数是属性名,属性值,逗号分隔,是设置一组样式,属性必须加引号,值如果是数字可以不用跟单位和引号
$(this).css("color","red");
③参数可以是对象形式,方便设置多组样式。属性名和属性值用冒号隔开,属性可以不用加引号
(注意:复合属性则必须采取驼峰命名法,属性值如果不是数字,则需要加引号)
$(this).css({"color":"red","font-size":"20px"});
3.2.2 设置类样式方法
作用等同于以前的classList,可以操作类样式,注意操作类里面的参数不要加点
①添加类
$('div').addClass('current');
②删除类
$('div').removeClass('current');
③切换类
$('div').toggleClass('current');
tab栏切换
<!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>tab切换</title>
<style>
.tab{
width: 618px;
height: 400px;
margin: 0 auto;
}
.tab_list {
/* border-bottom: 1px solid block; */
height: 40px;
background-color: rgb(211, 208, 208);
margin: 0 auto;
}
.tab_list li {
float: left;
height: 39px;
line-height: 39px;
padding: 0 20px;
text-align: center;
cursor: pointer;
list-style: none;
}
.tab_list .current {
background-color: rgb(157, 23, 23);
color: aliceblue;
}
.tab_con{
width: 600px;
height: 75px;
margin: 0 auto;
}
.item{
height: 60px;
padding: 10px;
margin: 10px auto;
}
.item_info {
padding: 20px 0 0 20px;
}
.item {
display: none;
}
</style>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div class="tab">
<div class="tab_list">
<ul>
<li class="current">商品介绍</li>
<li>规格与包装</li>
<li>售后保障</li>
<li>商品评价</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">
商品介绍模块
</div>
<div class="item">
手机社区模块
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('.tab_list li').click(function() {
$(this).addClass('current').siblings().removeClass('current');
let index = $(this).index();
$('.tab_con .item').eq(index).show().siblings().hide();
})
})
</script>
</body>
</html>
3.3 jQuery效果
语法:
show([speed,[easing],[fn]])
hide([speed,[easing],[fn]])
toggle([speed,[easing],[fn]])
特别的
fadTO([[speed],opacity,[easing],[fn]])
(1)opacity:透明度必须写,取值0~1之间
(2)speed: 三种预定速度之一的字符串("slow","normal", or "fast")或表示动画时长的毫秒数值(如:1000),必须写
animate(params,[speed],[easing],[fn])
(1)params: 想要更改的样式属性,以对象的形式传递,必须写。属性名可以不用带引号,如果是复合属性则需要采取驼峰命名法borderLeft。其余参数都可以忽略
等等类似
参数:
(1)参数都可以省略,无动画直接显示
(2)speed:三种预定速度之一的字符串(“slow”, “normal”, or “fast”)或表示动画时长的毫秒数值(如:1000)
(3)easing:(Optional)用来制定切换效果,默认是“swing”,可用参数“linear”
(4)fn:回调函数,在动画完成时执行的函数,每个元素执行一次。
鼠标事件切换
hover([over],out)
(1)over:鼠标经过时触发的函数,相当于mouseenter
(2)out:鼠标经过时触发的函数,相当于mouseleave
注意hover 里面的函数只写一个,鼠标经过离开都会触发
案例:高亮显示
<script>
$(function() {
//所有动画都有排队,要加stop()
$('.wrap li').hover(function() {
// 鼠标进入的时候,其他的li标签透明度:0.5
$(this).siblings().stop().fadeTo(400,0.5);
}, function() {
//鼠标离开其他的li透明的改为1
$(this).siblings().stop().fadeTo(400,1);
});
})
</script>
3.4 动画队列及其停止排队方法
3.4.1 动画或者效果队列
动画或者效果队列一旦触发就会执行,如果多次触发,就会造成多个动画或者效果排队执行。
3.4.2 停止排队
stop()
(1)stop() 方法用于停止动画效果
(2)注意:stop()写到动画或者效果的前面,相当于停止结束上一次的动画
3.4.3 案例 王者手风琴
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>王者荣耀手风琴效果</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 769px;
height: 115px;
margin:200px auto;
background: url("images/bg.png") no-repeat;
padding: 20px;
}
.img{
display: block;
}
ul{
list-style: none;
}
.box ul{
overflow: hidden;
}
.box li{
width: 69px;
height: 69px;
margin-right: 10px;
float: left;
position: relative;
}
.box .current{
width: 224px;
}
.box .current .big{
display: block;
}
.box .current .small{
display: none;
}
.big{
display: none;
width: 224px;
}
.small{
display: block;
position: absolute;
width: 69px;
height: 69px;
left: 0;
top: 0;
border-radius: 5px;
}
</style>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$("li").mouseenter(function () {
//当前小li宽度变为224px,同时里面的小图片淡出,大图片淡入
$(this).stop().animate({
width: 224
},200).find(".small").stop().fadeOut().siblings(".big").stop().fadeIn();
//其余兄弟小li宽度变为69px,小图片淡入,大图片淡出
$(this).siblings("li").stop().animate({
width: 69
},200).find(".small").stop().fadeIn().siblings('.big').stop().fadeOut();
});
})
</script>
</head>
<body>
<div class="box">
<ul>
<li class="current">
<a href="#">
<img src="images/姜子牙.jpg" alt="" class="small">
<img src="images/姜子牙.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/张飞.jpg" alt="" class="small">
<img src="images/张飞.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/成吉思汗.jpg" alt="" class="small">
<img src="images/成吉思汗.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/程咬金.jpg" alt="" class="small">
<img src="images/程咬金.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/貂蝉.jpg" alt="" class="small">
<img src="images/貂蝉.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/赵云.jpg" alt="" class="small">
<img src="images/赵云.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/达摩.jpg" alt="" class="small">
<img src="images/达摩.png" alt="" class="big">
</a>
</li>
</ul>
</div>
</body>
</html>
3.5 jQuery属性操作
3.5.1 获取元素固有属性
element.prop('属性名',[‘属性值’]) // 获取元素固有属性值
3.5.2 设置或获取元素自定义属性值
element.attr("属性", ["属性值"]) // 类似原生的getAttribute()和setAttribute()
注意:该方法也可以获取H5自定义属性,data-开头的
3.5.3 数据缓存
data()方法可以在指定的元素上存取数据,并不会修改DOM元素结构。一旦页面刷新,之前存放的数据都将被移除。
element.data("自定义属性名",["自定义属性值"])
注意:他还以读取H5自定义属性 data-index (不用写data-),得到的是数字型
3.6 jQuery内容文本值
主要针对元素的内容和表单的值操作
3.6.1 普通元素内容
html()(相当于原生innerHTML)
html(['内容']) //获取或设置元素内容
3.6.2 普通元素文本内容
text()(相当于原生innerText)
text(["文本内容"]) // 获取或设置文本内容
3.6.3 表单的值
val()(相当于原生的value())
val(["表单的值"]) // // 获取或设置表单的值
3.7 jQuery元素操作
主要是遍历、创建、添加、删除元素操作。
3.7.1 遍历元素
$('div').each(function(index, domEle){xxx;})
(1)each()方法遍历匹配的每一个元素。主要用DOM处理。each每一个
(2)里面的回调函数有两个参数:index是每个元素的索引号;demEle是每个DOM元素对象,不是jquery对象
(3)所以想要使用jquery方法,需要给这个元素转换为jquery对象$(domEle)
$.each(object, function(index, element){xxx;})
(1)$each()方法可用于遍历任何对象。主要用于数据处理,比如数组,对象
(2)里面的函数有2个参数,index是每个元素的索引号;element是遍历对象
3.7.2 创建元素
$('<li></li>');
动态的创建一个 < li>
3.7.3 添加元素
内部添加:
element.append('内容') // 追加到元素内部最后
element.prepend('内容'); // 添加到元素内部前边
外部添加:
element.after('内容'); // 追加到元素的后边
element.before('内容'); // 添加到元素的前边
3.7.3 删除元素
element.remove() // 删除匹配的元素(本身)
element.empty() // 删除匹配的元素集合中所有的子节点
element.html("") // 清空匹配的元素内容
3.7.4 案例
购物车
<!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>购物车</title>
<script src="js/jquery.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
/* nav */
input {
outline: none;
}
.container {
margin: 0 auto;
}
nav {
height: 80px;
background-color: #e9e6b8;
margin-bottom: 20px;
line-height: 80px;
padding: 0 40px;
}
nav ul {
width: 1100px;
}
nav ul li {
float: left;
list-style: none;
width: 170px;
height: 60px;
font-size: 20px;
}
nav ul li:nth-child(6) {
margin-left: 60px;
}
nav ul li:nth-child(6),
nav ul li:nth-child(7) {
width: 60px;
font-size: 16px;
}
.current {
background-color: #e0dfd7;
}
/* 购物车主体 */
div {
box-sizing: border-box;
}
.cart-head {
width: 1070px;
height: 50px;
background-color: #eeeddd;
padding-top: 15px;
padding-left: 10px;
}
.cart-head div,
.cart-head input {
float: left;
}
.cart-head input[type=checkbox] {
margin-right: 3px;
}
.commodity {
margin-left: 100px;
}
.price {
margin-left: 300px;
}
.num,
.sum,
.operation {
margin-left: 100px;
}
/* 商品内容模块 */
.cart-content {
margin-top: 10px;
}
.cart-content .item {
width: 1070px;
height: 200px;
border-top: 1px solid #ccc;
margin-bottom: 10px;
padding-left: 10px;
}
.item .box {
float: left;
width: 300px;
height: 100px;
margin-left: 50px;
margin-top: 50px;
}
.cart-content .item input {
display: block;
float: left;
margin-top: 90px;
background-color: #ccc;
}
.item .box img {
width: 145px;
float: left;
margin-right: 5px;
}
.item .box p {
text-indent: 2em;
width: 145px;
float: left;
font-size: 12px;
}
.item>div {
float: left;
margin-top: 100px;
}
.item-price {
margin-left: 107px;
}
.item-num {
margin-left: 70px;
}
.item-sum {
margin-left: 72px;
}
.item-opration {
margin-left: 90px;
color: red;
cursor: pointer;
}
.item-num span {
display: block;
width: 15px;
height: 20px;
float: left;
border: 1px solid #ccc;
margin-top: 0px;
text-align: center;
line-height: 17px;
cursor: pointer;
}
.item .item-num .nums {
float: left;
width: 35px;
height: 20px;
border: 1px solid #ccc;
text-align: center;
font-size: 12px;
line-height: 20px;
margin-top: 0;
}
/* 总计 */
.cart-footer {
width: 1070px;
height: 100px;
background-color: #eeeddd;
line-height: 90px;
padding-left: 10px;
}
.cart-footer .select-all input {
vertical-align: middle;
margin-top: -2px;
}
.cart-footer .select-all span {
vertical-align: middle;
display: inline-block;
}
.cart-footer>div {
float: left;
line-height: 100px;
}
.footer-total {
margin-left: 80px;
}
.footer-price {
margin-left: 70px;
}
.footer-num {
margin-left: 105px;
}
.footer-sum {
margin-left: 95px;
}
.footer-opration1 {
margin-left: 95px;
color: red;
cursor: pointer;
}
.footer-opration2 {
margin-left: 95px;
color: rgb(143, 28, 28);
cursor: pointer;
}
.footer-opration3 {
width: 100px;
margin-left: 60px;
font-size: 20px;
text-align: center;
color: #e9e6b8;
background-color: red;
cursor: pointer;
}
.w {
width: 1070px!important;
}
</style>
</head>
<body>
<div class="container w">
<div class="row">
<nav>
<ul>
<li>首页</li>
<li>服装</li>
<li>手机</li>
<li>电脑</li>
<li>日用</li>
<li>注册</li>
<li>登录</li>
</ul>
</nav>
</div>
<div class="row w">
<div class="cart-head">
<div class="select-all">
<input type="checkbox" name="" id="" class="checkall"> 全选
</div>
<div class="commodity">商品</div>
<div class="price">价格</div>
<div class="num">数量</div>
<div class="sum">小计</div>
<div class="operation">操作</div>
</div>
</div>
<!-- 商品详细模块 -->
<div class="row w">
<div class="cart-content">
<div class="item">
<input type="checkbox" name="" class="checkbox">
<div class="box">
<img src="images/姜子牙.jpg" alt="">
<p>月亮与六便士正版书籍 毛姆经典作品青少 世界经典文学名著书籍畅销书排行榜</p>
</div>
<div class="item-price">¥12.60</div>
<div class="item-num">
<span class="left">-</span>
<input type="text" value="1" class="nums">
<span class="right">+</span>
</div>
<div class="item-sum">¥12.60</div>
<div class="item-opration">删除</div>
</div>
<div class="item">
<input type="checkbox" name="" class="checkbox">
<div class="box">
<img src="images/张飞.jpg" alt="">
<p>月亮与六便士正版书籍 毛姆经典作品青少 世界经典文学名著书籍畅销书排行榜</p>
</div>
<div class="item-price">¥25.80</div>
<div class="item-num">
<span class="left">-</span>
<input type="text" value="1" class="nums">
<span class="right">+</span>
</div>
<div class="item-sum">¥25.80</div>
<div class="item-opration">删除</div>
</div>
<div class="item">
<input type="checkbox" name="" class="checkbox">
<div class="box">
<img src="images/成吉思汗.jpg" alt="">
<p>月亮与六便士正版书籍 毛姆经典作品青少 世界经典文学名著书籍畅销书排行榜</p>
</div>
<div class="item-price">¥32.10</div>
<div class="item-num">
<span class="left">-</span>
<input type="text" value="1" class="nums">
<span class="right">+</span>
</div>
<div class="item-sum">¥32.10</div>
<div class="item-opration">删除</div>
</div>
<div class="item">
<input type="checkbox" name="" class="checkbox">
<div class="box">
<img src="images/程咬金.jpg" alt="">
<p>月亮与六便士正版书籍 毛姆经典作品青少 世界经典文学名著书籍畅销书排行榜</p>
</div>
<div class="item-price">¥22.40</div>
<div class="item-num">
<span class="left">-</span>
<input type="text" value="1" class="nums">
<span class="right">+</span>
</div>
<div class="item-sum">¥22.40</div>
<div class="item-opration">删除</div>
</div>
</div>
</div>
<!-- 商品总计 -->
<div class="row w">
<div class="cart-footer">
<!-- 全选 -->
<div class="select-all">
<input type="checkbox" name="" id="" class="checkall">
<span>全选</span>
</div>
<div class="footer-opration1">删除选中商品</div>
<div class="footer-opration2">清空购物车</div>
<div class="footer-total">总计</div>
<div class="footer-num">
<span>1</span>
</div>
<div class="footer-sum">¥14.30</div>
<div class="footer-opration3">结算</div>
</div>
</div>
</div>
<script>
$(function() {
// 给nav导航栏中的li添加悬浮变字体颜色的效果(完全可以不用做)
$("nav li").stop().mouseenter(function() {
$(this).css({
color: 'red',
cursor: 'pointer'
});
}).stop().mouseleave(function() {
$(this).css('color', '#000');
});
getSum();
// 让全选按钮的checked属性的状态和所有item的复选框状态一致
// checked属性改变之后触发
$('.checkall').change(function(){
$('.checkbox, .checkall').prop('checked', $(this).prop('checked'));
// 当全选按钮发生改变,如果是选中状态给所有的item加current类
if ($(this).prop('checked')) {
$('.item').addClass('current');
} else {
$('.item').removeClass('current');
}
});
// 如果所有商品全选,那就把全选选上
// :checked 来判断选中个数
$('.checkbox').change(function() {
// console.log($('.item').length);
// console.log($('.checkbox:checked').length);
if ($('.checkbox:checked').length == $('.item').length) {
$('.checkall').prop('checked', true);
} else {
$('.checkall').prop('checked', false);
}
// 当点击每个item前面的复选框按钮时,如果是选中状态就添加current类
if ($(this).prop('checked')) {
$(this).parent('.item').addClass('current');
} else {
$(this).parent('.item').removeClass('current');
}
});
// 增加商品数量模块,点击加号时,让当前商品数量++
$('.item .right').click(function() {
let num = $(this).siblings('.nums').val();
num++;
$(this).siblings('.nums').val(num);
// 点击右侧按钮时候,当前的商品后面的小计也要做相应的改变
// 把价格中的数字截取出来*数目,再赋值给小计,赋值时+"¥"。
let price = $(this).parent('.item-num').siblings('.item-price').text().substr(1);
// 计算结果,保留两位小数
let sum = (price * num).toFixed(2);
// 给他爹的兄弟赋值
$(this).parent('.item-num').siblings('.item-sum').text("¥" + sum);
getSum();
});
// 减商品数量模块,点击减号时,让当前商品数量--
$('.item .left').click(function() {
let num = $(this).siblings('.nums').val();
// 数量不能小于1
if (num <= 1) {
return false;
}
num--;
$(this).siblings('.nums').val(num);
// 点击左侧按钮时候,当前的商品后面的小计也要做相应的改变
// 把价格中的数字截取出来*数目,再赋值给小计,赋值时+"¥"。
let price = $(this).parent('.item-num').siblings('.item-price').text().substr(1);
// 计算结果,保留两位小数
let sum = (price * num).toFixed(2);
// 给他爹的兄弟赋值
$(this).parent('.item-num').siblings('.item-sum').text("¥" + sum);
getSum();
});
// 当用户在input件数,输入框中自定义输入数字时,也要修改小计
$(".item .nums").change(function() {
let num = $(this).val();
// 如果输入的数值小于1,先给它赋值为1,并把总价格赋值为单价
if (num < 1) {
$(this).val(1);
// 获取当前价格
let price = $(this).parents('.item-num').siblings('.item-price').text().substr(1);
// 给item后面的总价赋值.toFixed()方法前面必须是数字类型的才行
price = parseFloat(price);
$(this).parents('.item-num').siblings('.item-sum').text("¥" + (price).toFixed(2));
getSum();
return false;
}
// 获取价格值
let price = $(this).parents('.item-num').siblings('.item-price').text().substr(1);
// 计算结果,保留两位小数
let sum = (price * num).toFixed(2);
// 给他爹的兄弟赋值
$(this).parents('.item-num').siblings('.item-sum').text("¥" + sum);
getSum();
});
// 计算总数和总价
function getSum() {
let count = 0; // 计算总数
let money = 0; // 计算总价
$(".item .nums").each(function(i, domele) {
// $(domele).val()是字符型,需要转化为数值型
count += parseInt($(domele).val());
})
// 给总计里面的数目赋值
$(".footer-num span").text(count);
$('.item .item-sum').each(function(i, ele) {
money += parseFloat($(ele).text().substr(1));
})
$(".footer-sum").text('¥' + money.toFixed(2));
// let priceSum = 0;
// $(".item .nums").each(function(i, domele) {
// // 获取当前元素的件数
// let num = parseInt($(domele).val());
// // 获取当前元素的价格
// let price = parseFloat($(this).parents('.item-num').siblings('.item-price').text().substr(1));
// priceSum += (num * price);
// })
// priceSum = priceSum.toFixed(2);
// // 给总价赋值
// $(".footer-sum").text('¥' + priceSum);
}
// 删除商品模块
// 用户点击每个item后面的删除按钮时,删除当前item
$(".item .item-opration").click(function() {
$(this).parents(".item").remove();
getSum();
})
// 当点击footer里面的删除选中时,删除勾选前面复选框的item
$(".footer-opration1").click(function() {
// 判断每个item前面的复选框是否被选中,如果选中删除他所对应的item即可
$(".item .checkbox:checked").parents(".item").remove();
getSum();
})
// 当点击footer里面的清空时,删除所有item
$(".footer-opration2").click(function() {
// 判断每个item前面的复选框是否被选中,如果选中删除他所对应的item即可
$(".item").remove();
getSum();
})
})
</script>
</body>
</html>
3.8 jQuery尺寸、位置操作
3.8.1 尺寸
语法 | 用法 |
---|---|
width() / height() | 取得匹配元素宽度和高度值 只算width/height |
innerWidth() / innerHeight() | 取得匹配元素宽度和高度值 包含padding |
outerWidth() / outerHeight() | 取得匹配元素宽度和高度值 包含padding和border |
outerWidth(true) / outerHeight(true) | 取得匹配元素宽度和高度值 包含padding、border和margin |
- 参数为空,则获取相应值,返回的是数字型
- 参数为数字,则修改相应的值。
3.8.2 位置
①offset()设置或获取元素偏移,返回的是对象
-
设置或者返回被选元素相对于文档的偏移坐标,跟父级有关系
-
该方法有两个属性 left、top。offset().top 用于获取距离文档顶部的距离,offset().left 用于获取距离文档左侧的距离
②position()获取元素偏移
-
返回被选元素相对于带有定位的父级偏移坐标,如果父级都没有定位,则以文档为准。
-
只能获取不能设置偏移量
③scrollTop()/scrollLeft()设置或者获取元素被卷去的头部和左侧
$(document).scrollTop(200);
$(window).scroll(function() {
console.log($(document).scrollTop());
if ($(document).scrollTop() >= 900) {
$('body, html').stop().animate({ //不能写doucument文档
scrollTop: 0 //scrollTop: 0平滑滚动
})
}
})
3.8.3 案例
电梯导航
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script src="js/jquery.min.js"></script>
<title>电梯导航</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
background-color: #fff;
}
body {
height: 3000px;
background-color: #f1f1f1;
}
.aside {
display: none;
position: fixed;
left: 1%;
top: 50%;
transform: translateY(-50%);
}
.aside li {
height: 40px;
line-height: 40px;
text-align: center;
cursor: pointer;
padding: 0 20px;
}
.aside li:hover {
background-color: green;
color: #fff;
}
.aside a {
display: block;
background-color: #fff;
text-align: center;
cursor: pointer;
padding: 10px 20px;
text-decoration: none;
color: #000;
}
.aside a:hover {
background-color: green;
color: #fff;
}
.active {
color: green;
}
.content {
width: 60%;
margin: 0 auto;
}
.box {
height: 380px;
margin-top: 20px;
background-color: #68945c;
}
.box:first-child {
margin-top: 0;
}
</style>
</head>
<body>
<!-- 左侧导航strat -->
<div class="aside">
<ul>
<li class="active">动漫</li>
<li>电视剧</li>
<li>电影</li>
<li>歌曲</li>
</ul>
<a href="#" class="back">
<span>/\</span>
<br />顶部
</a>
</div>
<!-- 左侧导航end -->
<!--中间内容strat -->
<div class="content">
<div class="box">动漫</div>
<div class="box tv">电视剧</div>
<div class="box">电影</div>
<div class="box">歌曲</div>
</div>
<!--中间内容end -->
<script>
$(function() {
// 当我点击li 不需要执行页面滚动添加的active操作
// 节流阀 互斥锁
// 默认打开节流阀
let flag = true;
// 显示
// 解决刷新不显示的问题
function toggleTool() {
if ($(document).scrollTop() >= $('.tv').offset().top) {
$('.aside').stop().fadeIn();
} else {
$('.aside').stop().fadeOut();
}
}
toggleTool();
$(window).scroll(function() {
toggleTool();
// 根据节流阀状态开启左侧li添加active操作
if(flag) {
// 页面滚动到某个内容区域,左侧导航li也要添加active
$('.content .box').each(function(i, ele) {
if ($(document).scrollTop() >= $(ele).offset().top) {
console.log(i);
$('.aside li').eq(i).addClass('active').siblings().removeClass();
}
})
}
});
// 点击跳转
$('.aside li').click(function() {
// 点击后,节流阀关闭
flag = false;
// 获取当前li索引号
console.log($(this).index());
// 每次点击,计算页面要去的位置
let current = $('.content .box').eq($(this).index()).offset().top;
// 页面滚动
$('body, html').stop().animate({
scrollTop: current
}, function() {
// 回调函数,当滚动完成再打开节流阀
flag = true;
});
// 点击之后,添加active类,其他删除
$(this).addClass('active').siblings().removeClass();
})
});
</script>
</body>
</html>
四、jQuery事件
4.1 jQuery事件注册
单个事件注册
element.事件(function() {})
4.2 jQuery事件处理
4.2.1 on()绑定事件
在匹配元素上绑定一个或多个事件处理函数
element.on(events,[selector],fn)
①events:一个或多个用空格分隔的事件类型(或者写不同函数事件对象),如‘click’或‘keydown’
②selector:元素的子元素选择器
③fn:回调函数 即绑定在元素生上的监听函数
④可以事件委派操作,就是把子元素身上的事件绑定在父元素身上
⑤动态创建的元素吗,click()没有办法动态绑定事件。on()可以给动态生成的元素绑定事件
4.2.2 off()事件解绑
off()可以移除通过on()方法添加的事件处理程序
element.off(events,[selector],fn)
特别地:one()事件只触发一次
4.3.3 trigger()自动触发事件
element.click() // 第一种简写方式
element.trigger('type') // 第二种自动触发模式
element.triggerHandler('type') // 第三种自动触发模式
// 不会触发元素的默认行为
4.3 jQuery事件对象
element.on(events, [selector], function(event) {})
阻止默认行为:event.preventDefault() 或者 return false
阻止冒泡:event.stopPropagation()
4.4 案例
发布微博留言
<!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>发布微博</title>
<script src="js/jquery.min.js"></script>
<style>
ul li {
display: none;
margin-right: 35px;
line-height: 25px;
border-bottom: 1px dashed #cccccc;
list-style: none;
}
a {
float: right;
text-decoration: none;
}
a:hover {
color: red;
}
.box {
position: relative;
margin: 50px auto;
width: 500px;
border: 1px solid black;
border-radius: 5px;
}
.box span {
display: block;
margin-bottom: 8px;
text-align: center;
font-family: '宋体' bold;
}
.box .txt {
display: block;
margin: auto;
}
.box .btn {
position: absolute;
top: 168px;
right: 80px;
border-radius: 5px;
color: aliceblue;
background-color: rgb(16, 16, 176);
}
</style>
</head>
<body>
<div class="box" id="weibo">
<span>微博发布</span>
<textarea name="" class="txt" cols="30" rows="10" maxlength="40"></textarea>
<button class="btn">发布</button>
<ul></ul>
</div>
<script>
$(function() {
$('.btn').on('click', function() {
if ($('.txt').val() == '') {
alert('输入内容不能为空!');
$('.txt').css('borderColor', 'red');
} else {
$('.txt').css('borderColor', 'black');
let li = $('<li></li>');
li.html($('.txt').val() + '<a href="javascript:;">删除</a>');
$('ul').prepend(li);
li.slideDown();
$('.txt').val('');
}
});
// 动态创建的a元素添加点击删除事件
$('ul').on('click', 'a', function() {
$(this).parents('li').slideUp(function() {
// 这里的this是$(this).parents('li')
$(this).remove();
});
})
})
</script>
</body>
</html>
五、jQuery其他方法
5.1 jQuery对象拷贝方法
$.extend([deep], target, object, [objectN])
① depp:如果设为true为深拷贝,默认为false 浅拷贝
② target:要拷贝到的目标对象
③ object1: 代拷贝第一个对象的对象
④ objectN: 代拷贝第N个对象的对象
⑤浅拷贝是把被拷贝的对象复杂数据类型中的地址拷贝给目标对象,修改目标对象会影响被拷贝对象
⑥深拷贝,前面加true,完全克隆(拷贝的对象,而不是地址),修改目标对象不会影响被拷贝对象
5.2 jQuery多库共存
解决jQuery和其他js库可能存在的多库共存问题
1、方法一:把jQuery里面的$标识符统一改为jQuery。比如:jQuery(‘div’)
2、方法二:jQuery变量规定新的名称:$.noConflict() let xx = $.noConflict();
5.3 jQuery插件
1、jQuery插件库:https://www.jq22.com/
2、jQuery之家: http://www.htmleaf.com/
3、全屏滚动(fullpage.js)
github: https://github.com/alvarotrigo/fullPage.js
中文翻译网站: https://www.dowebok.com/demo/2014/77/
4、bootstrap JS插件: https://v3.bootcss.com/
六、综合案例ToDoList
todolist.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>ToDoList—最简单的待办事项列表</title>
<link rel="stylesheet" href="css/todolist.css">
<script src="js/jquery.min.js"></script>
<script src="js/todolist.js"></script>
</head>
<body>
<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" name="" id="">
<p></p>
<a href="javascript:;"></a>
</li> -->
</ol>
<h2>已经完成 <span id="donecount"></span></h2>
<ul id="donelist">
<!-- <li>
<input type="checkbox" name="" id="">
<p></p>
<a href="javascript:;"></a>
</li> -->
</ul>
</section>
<footer>
Copyright © 2023 ssy.todolist.cn
</footer>
</body>
</html>
todolist.css
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;
}
}
todolist.js
$(function() {
// 1.按下回车,把完整数据存储到本地存储里面
// 存储数据格式 var todoist=[{title:"",done:false}]
load();
$('#title').on('keydown', function(e) {
if (e.keyCode == 13) { // 说明按下回车键
if ($(this).val() == '') {
alert('输入内容不能为空!')
} else {
// 先读取本地存储原来的数据
let local = getDate();
// console.log(local);
// 把local数组进行更新数据 把最新的数据追加local数组
local.push({title: $(this).val(), done: false});
// 把这个数组local存储给本地存储
saveDate(local);
// 2.todolist 本地存储数据渲染加载到页面
load();
$(this).val('');
}
}
});
// 3.删除操作
$('ol, ul').on('click', 'a', function() {
// 获取本地存储数据
let data = getDate();
// 修改数据
let index = $(this).attr('id');
data.splice(index, 1);
// 保存到本地存储
saveDate(data);
// 重新渲染
load();
})
// 4.todolist 正在进行和已完成选项操作
$('ol, ul').on('click', 'input', function() {
// 获取本地存储的数据
let data = getDate();
// 修改数据
let index = $(this).siblings('a').attr('id');
data[index].done = $(this).prop('checked');
// 保存到本地存储
saveDate(data);
// 重新渲染
load();
})
// 读取本地存储的数据函数
function getDate() {
let data = localStorage.getItem('todolist');
if (data != null) {
// 返回转化为数组对象格式的数据
return JSON.parse(data);
} else {
return [];
}
}
// 保存本地存储数据
function saveDate(data) {
localStorage.setItem('todolist', JSON.stringify(data));
}
// 渲染加载数据
function load() {
// 读取本地存储数据
let data = getDate();
// 遍历之前,清空ol里面的元素
$('ol, ul').empty();
let todoCount = 0; // 正在进行的个数
let doneCount = 0; // 已经完成的个数
$.each(data, function(i, m) {
// console.log(m); // m代表数据
if (m.done) {
$('ul').prepend('<li><input type="checkbox" checked><p>'+m.title+'</p><a href="javascript:;" id='+ i +'></a></li>');
doneCount++;
} else {
$('ol').prepend('<li><input type="checkbox"><p>'+m.title+'</p><a href="javascript:;" id='+ i +'></a></li>');
todoCount++;
}
});
$('#todocount').text(todoCount);
$('#donecount').text(doneCount);
}
})