jQuery
1.jQuery的概念
jQuery是一个兼容多浏览器的JavaScript库(函数库),核心理念是write less,do more(写得更少,做得更多)。jQuery,顾名思义,也就是JavaScript和查询(Query),即是辅助JavaScript开发的库
jQuery的特点:jQuery是一个快速的简洁的JavaScript框架,可以简化查询DOM对象、处理事件、制作动画、处理Ajax交互过程。
- 提供了强大的功能函数
- 解决浏览器兼容性问题
- 纠正错误的脚步知识
- 体积小,使用灵巧(只需引入一个js文件)
- 易扩展、插件丰富
jQuery的作用:
- 程序员的角度:简化JavaScript和Ajax编程,能够使程序员从设计和书写繁杂的JS应用中解脱出来,将关注点转向功能需求而非实现 细节上,从而提高项目的开发速度。
- 用户体验的角度:改善了页面视觉效果,增强了与页面的交互性,体验更绚丽的网页物资。
2.jQuery的引入
<!-- 1. 本地引入js框架 -->
<!-- <script src="jQuery.js"></script> -->
<!-- 2. 在线引入 -->
<script type="text/javascript"src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
3.jQueryDom和原生dom的相互转换
原生dom和jQueryDomAPI是完全不同的
jQueryDom没有单个的概念,所有获取的元素都放在包装集中(包装集类似于数组,存放的都是jQueryDom,也就是说,jQuery的单个元素也存放在包装集中)
需求:学习原生dom和 jQueryDom的相关API,因为不同的场景要使用不同的功能
jQueryDom转原生Dom
console.log($("#test").html());
get获取下标对应的原生dom
let oTest = $("#test").get(0);
console.log(oTest.innerHTML);
// let oDiv = $("div").get(1);
let oDiv = $("div")[2];
console.log(oDiv.innerHTML);
原生Dom转jQueryDom
let oDiv = document.getElementById("test");
console.log($(oDiv).html());
4.原生的延迟加载
对于js中的原生延迟加载
window.onload = function(){
}
jQuery的延迟加载
$是jQuery的简写,jQuery是该框架的核心函数对象
ready是通过jQuery的document调用的方法
$(document).ready(function(){
console.log("heiheihei");
});
简写:
$(function(){
console.log("heiheihei");
});
$(document).ready(function(){})和window.onload的区别
- ready表示文档已加载完成(不包含图片等非文字媒体文件)
- onload是指页面包含图片在内的所有元素都加载完成
- $(document).ready(function(){})要比window.onload先执行
5.jQuery基础选择器
- id选择器
- 类选择器
- 遍历选择器 eq
- 标签选择器
- 通用选择器
- 群组选择器
<!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>Document</title>
</head>
<body>
<div id="box1" class = "box">
本周要上7天班
</div>
<div id="box2" class = "box">
1
</div>
<div id="box3" class = "box">
1
</div>
<p>2</p>
<p>2</p>
<span>3</span>
<strong>4</strong>
</body>
</html>
<script src="jQuery.js"></script>
<script>
// id选择器
$("#box1").css({
backgroundColor:"red",
fontSize:36
});
// 类选择器
$(".box").css({
backgroundColor:"yellow"
});
// 遍历选择器 eq
$(".box:eq(1)").css({
backgroundColor:"hotpink"
});
let n = 2;
$(".box").eq(n).css({//连缀模式,每次完成一个功能后还是会返回一个包装集
backgroundColor:"skyblue"
});
// 标签选择器
$("p").css({
backgroundColor:"green"
});
// 通用选择器
$("*").css({
backgroundColor:"orange"
});
//群组选择器
$("p,span").css({
backgroundColor:"orange"
});
</script>
属性选择器
<body>
<div id="box1" class="">
1
</div>
<div id="" name="">
1
</div>
<input type="text">
<input type="button" value="哈哈哈">
</body>
</html>
<script src="jQuery.js"></script>
<script>
// 1.通过属性名获取元素
$("div[class]").css({
backgroundColor: "red"
});
$("div[id][name]").css({
backgroundColor: "yellow"
});
// 2.通过属性值获取
$("input[type=text]").css({
backgroundColor: "green"
});
</script>
伪类选择器
<script>
// 获取偶数下标的div
// :even
$("div:even").css({
backgroundColor:"red"
});
// 奇数行
// :odd
$("div:odd").css({
backgroundColor:"yellow"
});
// 第一个元素
// :first
$("div:first").css({
backgroundColor:"blue"
});
// 最后一个元素
// :last
$("div:last").css({
backgroundColor:"green"
});
// 除了
// :not
// $("div:not(#box2)").css({
// backgroundColor:"gold"
// });
$("div").not($("#box3")).css({
backgroundColor:"gold"
});
// 小于
// :lt
$("div:lt(2)").css({
backgroundColor:"hotpink"
});
// 大于
// :gt
$("div:gt(2)").css({
backgroundColor:"skyblue"
});
</script>
6.jQueryDom元素的遍历
兄弟节点的遍历:
- next 下一个元素
- nextAll 下一堆
- prev 上一个
- prevAll 上一堆
- siblings([标签名]) 除了该标签外的所有兄弟标签
父找子:
- find(“子元素”) : 后代
- children([“子元素”]) : 子代
子找父:
- parent() 找一个爹
- parents() 找祖宗
<script>
//兄弟节点的遍历
// next 下一个元素
// $("#box1").next().css({
// backgroundColor:"red"
// });
// // nextAll 下一堆
// $("#box1").nextAll().css({
// backgroundColor:"yellow"
// });
// prev 上一个
// $("#box1").prev().css({
// backgroundColor:"red"
// });
// $("#box3").prevAll().css({
// backgroundColor:"red"
// });
// siblings([标签名])
// $("#box1").siblings("div").css({
// backgroundColor:"red"
// });
// 父找子
// find("子元素") : 后代
// $("body").find("ul").css({
// backgroundColor:"red"
// });
// children(["子元素"]) : 子代
// $("body").children().css({
// backgroundColor:"red"
// });
// 子找父
// parent 找一个爹
// $("p").eq(2).parent().css({
// backgroundColor:"red"
// });
// parents 找祖宗
$("p").eq(2).parents().css({
backgroundColor:"red"
});
</script>
7.文本
有参数为写,无参为读
innerHTML == html( )
<script>
// 有参为写,无参为读
// innerHTML == html()
// 写
// $("div").eq(0).html("哈哈哈");
// 读
// console.log($("div").eq(0).html());
// let str = "hahaha";
// str += "xixixi";
// $("div").eq(0).html(str);
// value == val()
// 写
$("input").val("8888");
// 读
console.log($("input").val());
</script>
8.事件
$(“button”).click([传给事件体的参数],回调函数)
<script>
// $("button").click([传给事件体的参数],回调函数)
// $("button").click(function(){
// console.log("heihei");
// });
// $("div").click(function(){
// $(this).css({
// backgroundColor:"red"
// });
// });
// $("div").mouseover(function(){
// $(this).css({
// backgroundColor:"yellow"
// });
// });
// $("div").mouseout(function(){
// $(this).css({
// backgroundColor:"blue"
// });
// });
//jQuery的事件可以允许从外界传参给事件体
// 事件对象
$(document).click({name:"老王",age:18},function(evt){
//如何获取参数
//事件对象.data属性
console.log(evt.data.name,evt.data.age);
});
</script>
9.简单动画
-
隐藏:$(“div”).hide([时间间隔],[过渡效果],[回调函数]);
显示:show( );
切换(显示和隐藏切换):toggle( )
// 1.基本动画 // $("button").eq(0).click(function () { // // $("div").hide([时间间隔],[过渡效果],[回调函数]); // $("div").hide(2000, function () { // console.log("嘿嘿嘿"); // }); // }); // $("button").eq(1).click(function () { // // $("div").hide([时间间隔],[过渡效果],[回调函数]); // $("div").show(2000); // }); // $("button").eq(2).click(function () { // // $("div").hide([时间间隔],[过渡效果],[回调函数]); // toggle表示切换如果显示则隐藏,如果隐藏则显示;arguments.callee表示调用toggle函数自身 // $("div").toggle(1000, arguments.callee); // });
-
上滑下滑
上滑:slideUp( )
下滑:slideDown( )
切换(上滑下滑):slideToggle( )
$("button").eq(0).click(function () { $("div").slideUp(2000, function () { console.log("嘿嘿嘿"); }); }); $("button").eq(1).click(function () { $("div").slideDown(2000); }); $("button").eq(2).click(function () { // $("div").hide([时间间隔],[过渡效果],[回调函数]); $("div").slideToggle(500, arguments.callee); });
-
淡入淡出
淡入:fadeOut( )
淡出:fadeIn( )
切换(淡入淡出):fadeToggle( )
$("button").eq(0).click(function () { $("div").fadeOut(2000, function () { console.log("嘿嘿嘿"); }); }); $("button").eq(1).click(function () { $("div").fadeIn(2000); }); $("button").eq(2).click(function () { $("div").fadeToggle(500, arguments.callee); });
10.自定义动画
自定义动画可以操作offset相关属性,进行动画效果
animate({offset相关操作},[时间间隔],[过渡效果],[回调函数])
<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>Document</title>
<style>
#box{
width: 100px;
height: 100px;
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<button>启动</button>
<div id="box"></div>
</body>
</html>
<script src="jQuery.js"></script>
<script>
// 自定义动画可以操作offset相关属性,进行动画效果
// animate({offset相关操作},[时间间隔],[过渡效果],[回调函数])
$("button").eq(0).click(function(){
$("#box").animate({
width:200,
height:50,
left:800
},1500).animate({
top:500
},1000).animate({
left:0
},1000).animate({
top:100
},1000);
});
</script>
11.jQueryDom属性操作(读写)
- 普通属性
//普通属性读写
// attr
// prop
//读
// console.log($("#test").attr("id"));
//写
$("#test").attr("id", "heihei");
//添加自定义属性
//单个添加
// $("#test").attr("a","666");
//批量添加
// $("#test").attr({
// "b":1,
// "c":2,
// "d":3
// });
// if($("input").attr("checked") == "checked"){
// console.log("可以登录");
// }
//prop返回true或false
// if($("input").prop("checked") == true){
// console.log("可以登录");
// }
- style属性读写
//style属性读写
// css
// 读
// 单个的读
// console.log($("#test").css("backgroundColor"));
// console.log($("#test").css("fontSize"));
// console.log($("#test").css("width"));
// 批量的读
// console.log($("#test").css(["fontSize","backgroundColor"]));
// 写
// $("#test").css({
// backgroundColor:"green",
// });
- offset属性读写
//offset属性读写
//witdh height
//读
// console.log($("#test").width());
// console.log($("#test").height());
// //写
// console.log($("#test").width(500));
// console.log($("#test").height(600));
//left top
//offset:很银杏的添加了绝对定位
//写
// $("#test").offset({
// left:500,
// top:600
// });
//读
// console.log($("#test").offset().left);
// console.log($("#test").offset().top);
12.dom的增删
-
增
// let oDiv = $("<div>"); // oDiv.html(9999); let oDiv = $("<div>hahahaha</div>"); $("body").append(oDiv);
-
追加
尾插,头插,插入目标节点之后,插入目标节点之前
// let oLi = $("<li>老六</li>"); //尾插 // $("ul").append(oLi); // oLi.appendTo($("ul")); //头插 // $("ul").prepend(oLi); // oLi.prependTo($("ul")); //插入目标节点之后 // $("li").eq(2).after(oLi); // oLi.insertAfter($("li").eq(2)); //插入目标节点之前 // $("li").eq(2).before(oLi); // oLi.insertBefore($("li").eq(2));
-
删
//删 // remove // $("li").eq(2).remove(); // empty // $("li").eq(2).empty();
13.瀑布流
<!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>Document</title>
<style>
div{
position: absolute;
width: 200px;
}
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
// 瀑布流特点:必须是定宽或者定高
class WaterFall{
createDiv(){
for(let i=0; i<14; i++){
let oDiv = $("<div>");
$("body").append(oDiv);
//高,宽,背景图,序号
//高 50~350的区间
let rnd = Math.round(Math.random()*300+50);
oDiv.css({
height:rnd,
backgroundImage:`url(img/${i}.jpg)`,
backgroundSize:`200px ${rnd}px`,
});
oDiv.html(i);
}
this.change();
}
change(){
//页面的宽能放多少个div
let n = Math.floor(innerWidth/210);
//获取页面所有div
let oDivs = $("div");
//记录每一列的高度
let arrH = [];
for(let i=0; i<oDivs.length; i++){
//第一行
if(arrH.length < n){
oDivs.eq(i).css({
left:i*210,
top:0
});
arrH.push(oDivs.eq(i).height());
}else{//除了第一行
let index = this.findMin(arrH);
oDivs.eq(i).css({
left:index*210,
top:arrH[index] + 10
});
arrH[index] += oDivs.eq(i).height() + 10;
}
}
}
findMin(arrH){
let min = 0;
for(let i=0; i<arrH.length; i++){
if(arrH[min] > arrH[i]){
min = i;
}
}
return min;
}
scroll(){
let that = this;
$(window).scroll(function(){
//scrollTop:代表滚动条高度
if($(window).scrollTop()>400){
that.createDiv();
}
});
}
}
let wf = new WaterFall();
wf.createDiv();
wf.createDiv();
wf.createDiv();
wf.scroll();
</script>
14.ajaxLoad
load get post 中层
getScript getJSON 高层
ajax 底层
jQueryDom.load(请求的资源地址,[请求参数],[回调函数]);
-
作用:将返回的响应添加至jQueryDom的html(),用来请求html静态文件,实现页面的头尾分离
-
html文件
<body> <!-- <div id="box"></div> --> <header></header> <section></section> <footer></footer> </body> </html> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> // load get post 中层 // getScript getJSON 高层 // ajax 底层 // 作用:将返回的响应添加至jQueryDom的html(),用来请求html静态文件,实现页面的头尾分离 // jQueryDom.load(请求的资源地址,[请求参数],[回调函数]); // $("#box").load("4.load.txt"); // $("header").load("4.html",function(){ // $("li").click(function(){ // console.log($(this).html()); // }); // }); // $("header").load("4.html"); </script>
-
css文件
<style type="text/css"> *{ margin: 0; padding: 0; } header{ height: 100px; background: yellow; } header ul{ height: 100px; width: 800px; position: relative; margin: 0 auto; opacity: 0.5; } header ul li{ list-style: none; width:150px; background: red; text-align: center; line-height: 100px; border: 1px solid black; float: left; } section{ height: 300px; background: green; opacity: 0.3; } footer{ height: 300px; background: blue; opacity: 0.3; } </style>
-
js文件
$("li").click(function(){ console.log($(this).html()); });
-
txt文件
我要好好学习
15.getAndPost
- get : $.get(“url”,“请求参数”,“回调函数”):返回值是promise对象
- post : $.post(“url”,“请求参数”,“回调函数”):返回值是promise对象
get和post传参的异同?
1.post的安全性高于get;如果以get方式请求,请求参数会拼接到url后面,安全性性低,以post方式请求,请求参数会包裹在请求体中,安全性更高
2.数量区别:get方式传输的数据量小,规定不能超过2kb,post方式请求数据量大,没有限制。
3.传输速度:get的传输速度高于post
<script>
// $.get("url","请求参数","回调函数"):返回值是promise对象
// $.get("5.php","name=laowang&pwd=666",function(resText,stats,xhr){
// console.log(resText);
// // console.log(stats);
// // console.log(xhr);
// });
// $.get("5.php",{name:"小明",pwd:999},function(resText){
// console.log(resText);
// });
// $.get("5.php",{name:"yingyingying",pwd:3333}).then(function(resText){
// console.log(resText);
// });
//-----------------------
$.post("5.php","name=laowang&pwd=666",function(resText,stats,xhr){
console.log(resText);
// console.log(stats);
// console.log(xhr);
});
$.post("5.php",{name:"小明",pwd:999},function(resText){
console.log(resText);
});
$.post("5.php",{name:"yingyingying",pwd:3333}).then(function(resText){
console.log(resText);
});
//---------------------
// get和post传参的异同?
// 1.post的安全性高于get;如果以get方式请求,请求参数会拼接到url后面,安全性性低,
// 以post方式请求,请求参数会包裹在请求体中,安全性更高
// 2.数量区别:get方式传输的数据量小,规定不能超过2kb,post方式请求数据量大,没有限制。
// 3.传输速度:get的传输速度高于post
</script>
16.ajax
<script>
$.ajax({
type: "POST",
url: "5.php",
data: "name=John&pwd=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
</script>
17.getScript
$.getScript(“url”,回调函数);
- html文件
<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>Document</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<button>变色</button>
<div id="box"></div>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<!-- <script src="randColor.js"></script> -->
<script>
// $("button").click(function(){
// changeColor($("#box"));
// });
$("button").click(function(){
// $.getScript("url",回调函数);
$.getScript("randColor.js",function(){
changeColor($("#box"));
});
});
- js文件
function changeColor(box){
let color = Math.round(Math.random()*0xFFFFFF);
box.css({
backgroundColor:"#"+color
});
}