一、什么是jquery
是轻量级的就是库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器
jQuery是一种快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。
另外它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。(https://jquery.cuishifeng.cn/index.html)
二、jquery对象
jQuery 对象就是通过jQuery包装DOM对象后产生的对象。jQuery 对象是 jQuery 独有的. 如果一个对象是 jQuery 对象, 那么它就可以使用 jQuery 里的方法: $(“#test”).html();
$("#test").html()
//意思是指:获取ID为test的元素内的html代码。其中html()是jQuery里的方法
// 这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML;
//虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错
//约定:如果获取的是 jQuery 对象, 那么要在变量前面加上$.
var $variable = jQuery 对象
var variable = DOM 对象
$variable[0]:jquery对象转为dom对象 $("#msg").html(); $("#msg")[0].innerHTML
jquery的基础语法:$(selector).action()
*$写成jQuery也可以,$使用方便。
引入方法:<script src="jquery-3.4.1.min.js"></script>
三、寻找元素
1、选择器
基本选择器
$("*") $("#id") $(".class") $("element") $(".class,p,div")
层级选择器
$(".outer div") $(".outer>div") $(".outer+div") $(".outer~div")
基本筛选器
$("li:first") $("li:eq(2)") $("li:even") $("li:gt(1)")
属性选择器
$('[id="div1"]') $('["alex="sb"][id]')
表单选择器
$("[type='text']")----->$(":text") 注意只适用于input标签 : $("input:checked")
例子:
<body>
<div>hello div</div>
<p id="p1" mark="bb">pppp</p>
<p id="p3" mark="sb">pppp</p>
<a href="">click</a>
<p id="p2">ppp</p>
<div class="outer">
<div class="inner">inner
<p>inner p</p>
</div>
<p>son</p>
outer
</div>
<p>job</p>
<div class="outer2">steven</div>
<p>littlepppp</p>
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
<li>5555</li>
</ul>
<input type="text">
<input type="checkbox">
<input type="submit">
<script src="jquery-3.4.1.min.js"></script>
<script>
//基本选择器
$("div").css("color","red");
$("*").css("color","red");
$("#p1").css("color","blue");
$(".outer").css("color","yellow");//拿到多个标签,会自动遍历
$(".inner,p,div").css("color","green");
//层级选择器
$(".outer p").css("color","red");//后台选择器
$(".outer>p").css("color","red");//子代选择器
$(".outer+p").css("color","red")//毗邻
$(".outer~p").css("color","red")//找兄弟标签,不一定紧挨着 都是往下找
//基本筛选器
console.log($("ul li"))
$("li:first").css("color","red");
$("li:last").css("color","red");
$("li:eq(1)").css("color","red");//筛选出第二个。
$("li:even").css("color","red");//奇数
$("li:odd").css("color","red");//偶数
$("li:gt(1)").css("color","red");//从第二个开始(2,3,4)
$("li:lt(2)").css("color","red");//第二个之前(0,1)
//属性选择器
$("[mark]").css("color","red");
$("[mark='sb']").css("color","red");
$("[mark='sb'][id='p3']").css("color","red");//通过多个属性查找
$("[type='text']").css("width","300px");
//表单选择器
$(":text").css("width","400px");//第二种方式简写,只有input表单可以这样写
</script>
</body>
2、筛选器
过滤筛选器
$("li").eq(2) $("li").first() $("ul li").hasclass("test")
查找筛选器
$("div").children(".test") $("div").find(".test")
$(".test").next() $(".test").nextAll() $(".test").nextUntil()
$("div").prev() $("div").prevAll() $("div").prevUntil()
$(".test").parent() $(".test").parents() $(".test").parentUntil()
$("div").siblings()
例子:
<body>
<div>hello div</div>
<p id="p1" mark="bb">pppp</p>
<p id="p3" mark="sb">pppp</p>
<a href="">click</a>
<p id="p2">ppp</p>
<div class="outer">
<div class="inner">inner
<p>inner p</p>
</div>
<p>son</p>
outer
</div>
<p>job</p>
<div class="outer2">steven</div>
<p>littlepppp</p>
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
<li>5555</li>
<li id="end">6666</li>
<li>7777</li>
</ul>
<input type="text">
<input type="checkbox">
<input type="submit">
<script src="jquery-3.4.1.min.js"></script>
<script>
//$("li:eq(2)").css("color","red") 之前的写法
//第二种写法,推荐 过滤筛选器
$("li").eq(2).css("color","red");
$("li").first().css("color","red");
$("li").last().css("color","red");
//查找筛选器
$(".outer").children("p").css("color","red");//找子代这一层
$(".outer").find("p").css("color","red");//找后代所有的p
$("li").eq(1).next().css("color","red");//下面的一个
$("li").eq(1).nextAll().css("color","red");//下面的所有
$("li").eq(1).nextUntil("#end").css("color","red");//一直找到end为止
$("li").eq(3).prev().css("color","red");//找上面一个
$("li").eq(3).prevAll().css("color","red");//找上面所有
$(".outer .inner p").parent().css("color","red");//找父级
$(".outer .inner p").parents().css("color","red");//一直找父级,直到顶级,很少用这种
$(".outer .inner p").parentsUntil("body").css("color","red");//往上找直到父级是body
$(".outer").siblings().css("color","red");
</script>
</body>
四、操作元素
1、属性操作
--------------------------属性 $("").attr(); $("").removeAttr(); $("").prop(); $("").removeProp(); --------------------------CSS类 $("").addClass(class|fn) $("").removeClass([class|fn]) --------------------------HTML代码/文本/值 $("").html([val|fn]) $("").text([val|fn]) $("").val([val|fn|arr]) --------------------------- $("").css("color","red")
例子:
<body> <div class="div1" con="c1"></div> <input type="checkbox" checked="checked">是否可见 <input type="checkbox">是否可见 <input type="text" value="123"> <div value="456"></div> <div id="id1"> uuuu <p>ppp</p> </div> <script src="jquery-3.4.1.min.js"></script> <script> console.log($("div").hasClass("div1")); console.log($("div").attr("con")); console.log($("div").attr("con","c2")); console.log($(":checkbox:first").attr("checked")); //checked console.log($(":checkbox:last").attr("checked"));//attr主要用于找自定义的属性 //undefined console.log($(":checkbox:first").prop("checked")); //true console.log($(":checkbox:last").prop("checked")); //false console.log($("div").prop("class"));//prop主要用于找自有的属性 console.log($("#id1").html());//所有内容 如<p>ppp</p> console.log($("#id1").text());//只是文本 ppp console.log($("#id1").html("<h1>hahaha</h1>"));//进行替换 console.log($("#id1").text("<h1>hahaha</h1>")); //固有属性 console.log($(":text").val()); console.log($(":text").next().val()); $(":text").val("789"); $("div").css({"color":"red","background-color":"green"})
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。 像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此 需要使用prop方法去操作才能获得正确的结果。
jquery循环
<body> <p>0000</p> <p>1111</p> <p>2222</p> <script src="jquery-3.4.1.min.js"></script> <script> arr=[11,22,33]; // for (var i=0;i<arr.length;i++){ // $("p").eq(i).html(arr[i]) // } //循环遍历的方式一 $.each(arr,function(x,y){ console.log(x); //0 1 2 console.log(y); //11 22 33 }); //方式二 $("p").each(function(){ console.log($(this)); $(this).html("hello") }) </script> </body>
4.2文档处理
例子:
<body>
<div class="c1">
<p>pppp</p>
</div>
<button>add</button>
<script src="jquery-3.4.1.min.js"></script>
<script>
$("button").click(function(){
// $(".c1").append("<h1>hello</h1>");
var $ele=$("<h1></h1>");//创建一个便签
$ele.html("hello world");
//内部插入
$(".c1").append($ele);//写法1
$ele.appendTo(".c1");//写法2
$(".c1").prepend($ele);//追加到前面
$ele.prependTo(".c1");//写法2
//外部插入
$(".c1").after($ele);//插入到后面
$ele.insertAfter(".c1");//写法2
$(".c1").before($ele);
$ele.insertBefore(".c1");
//替换
$("p").replaceWith($ele);
//删除与清空
$(".c1").empty();
$(".c1").remove();
//复制
$(".c1").clone()
})
</script>
</body>
扩展:
//内部插入 $("").append(content|fn) ----->$("p").append("<b>Hello</b>"); $("").appendTo(content) ----->$("p").appendTo("div"); $("").prepend(content|fn) ----->$("p").prepend("<b>Hello</b>"); $("").prependTo(content) ----->$("p").prependTo("#foo"); //外部插入 $("").after(content|fn) ----->$("p").after("<b>Hello</b>"); $("").before(content|fn) ----->$("p").before("<b>Hello</b>"); $("").insertAfter(content) ----->$("p").insertAfter("#foo"); $("").insertBefore(content) ----->$("p").insertBefore("#foo");
实例:clone
<body> <div class="outer"> <div class="item"> <button onclick="add(this)">+</button> <input type="text"> </div> </div> <script src="jquery-3.4.1.min.js"></script> <script> function add(self){ var $clone_obj=$(self).parent().clone(); $clone_obj.children("button").html("-").attr("onclick","remove_obj(this)"); $(".outer").append($clone_obj) } function remove_obj(self){ $(self).parent().remove() } </script> </body>
4.3、css操作
CSS $("").css(name|pro|[,val|fn]) 位置 $("").offset([coordinates]) //视口偏移量 $("").position() //已定位父便签的偏移量 $("").scrollTop([val]) //滚动条,(实例返回顶部) $("").scrollLeft([val]) 尺寸 $("").height([val|fn]) $("").width([val|fn]) $("").innerHeight() $("").innerWidth() $("").outerHeight([soptions]) $("").outerWidth([options])
offset,position
<style>
*{
margin:0px;
padding:0px;
}
.div1{
200px;
height:200px;
background-color: red;
border:5px solid rebeccapurple;
padding: 20px;
margin:10px;
}
.div2{
200px;
height:200px;
background-color: blue;
}
.outer{
position:relative;
}
</style>
<body>
<div class="div1"></div>
<div class="outer">
<div class="div2"></div>
</div>
<script src="jquery-3.4.1.min.js"></script>
<script>
//offset()相对于视口的偏移量
// console.log($(".div1").offset().top);
// console.log($(".div1").offset().left);
//
// console.log($(".div2").offset().top);
// console.log($(".div2").offset().left);
//position()相对于已定位的父标签的偏移量
// console.log($(".div1").position().top);
// console.log($(".div1").position().left);
//
// console.log($(".div2").position().top);//父标签已定位,这里就是o,没定位就是200.
// console.log($(".div2").position().left);
//css操作 获取尺寸
console.log($(".div1").height());//只是内容区域的大小, 里面加参数相当于css定义高度 200
console.log($(".div1").innerHeight());//包含了padding 240
console.log($(".div1").outerHeight());//包含了border 250
console.log($(".div1").outerHeight(true));//包含了margin 270
</script>
五、事件
语法:
事件处理 $("").on(eve,[selector],[data],fn) // 在选择元素上绑定一个或多个事件的事件处理函数。 // .on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如: // $('ul').on('click', 'li', function(){console.log('click');})就是筛选出ul下的li给其绑定 // click事件; [selector]参数的好处: 好处在于.on方法为动态添加的元素也能绑上指定事件;如: //$('ul li').on('click', function(){console.log('click');})的绑定方式和 //$('ul li').bind('click', function(){console.log('click');})一样;我通过js给ul添加了一个 //li:$('ul').append('<li>js new li<li>');这个新加的li是不会被绑上click事件的 //但是用$('ul').on('click', 'li', function(){console.log('click');}方式绑定,然后动态添加 //li:$('ul').append('<li>js new li<li>');这个新生成的li被绑上了click事件 [data]参数的调用: function myHandler(event) { alert(event.data.foo); } $("li").on("click", {foo: "bar"}, myHandler)
例子:
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.4.1.min.js"></script>
<script>
//加载事件
// $(document).ready(function(){
// $("ul li").html(5555)
// });
// 简写形式
// $(function(){
// $("ul li").html(5555)
// })
</script>
</head>
<body>
<ul>
<li>11111</li>
<li>22222</li>
<li>33333</li>
<li>44444</li>
<li>55555</li>
<li>66666</li>
</ul>
<button>add</button>
<script src="jquery-3.4.1.min.js"></script>
<script>
//绑定事件,写法1
// $("ul li").click(function(){
// alert(6666)
// });
//写法2
// $("ul li").bind("click",function(){
// alert(6666)
// });
//事件委托
//问题,新增加的便签没有绑定事件。解决方法是使用事件委托on。
$("ul").on("click","li",function(){
alert(6666)
});
// $("ul li").unbind("click");//解除绑定
$("button").click(function(){
var $ele=$("<li>");
var len=$("ul li").length;
$ele.html((len+1)*11111);
$("ul").append($ele)
})
</script>
</body>
六、动画效果
例子:显示隐藏
<body> <div>hello</div> <button onclick="f1()">显示</button> <button onclick="f2()">隐藏</button> <button onclick="f3()">切换</button> <script> function f1(){ // $("div").show(); $("div").show(1000);//加参数表示1秒完成动作 } // function f2(){ // // $("div").hide(); // $("div").hide(1000); // } function f3(){ // $("div").toggle(); $("div").toggle(1000);//内部相当于有两个方法hide和show,当前是hide,就切换成show } //slideDown() 滑动出现 //slideUp() 隐藏 //slideToggle 切换 //fadeIn 淡入效果 //fadeOut 淡出 //fadeToggle 切换 //fadeTo(0.4) 调到设定的值 fadeTo(1000,0.4) //回调函数 function f2(){ // $("div").hide(); $("div").hide(1000,function(){ alert(11111) }); } </script> </body>
七,扩展方法
1、用JQuery写插件时,最核心的方两个方法
语法:
<script> $.extend(object) //为JQuery 添加一个静态方法。 $.fn.extend(object) //为JQuery实例添加一个方法。 jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); console.log($.min(3,4)); //----------------------------------------------------------------------- $.fn.extend({ "print":function(){ for (var i=0;i<this.length;i++){ console.log($(this)[i].innerHTML) } } }); $("p").print(); </script>
例子:
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.4.1.min.js"></script>
</head>
<body>
<p>pppp</p>
<p>0000</p>
<p>2222</p>
<script>
$.extend({
Myprint:function(){
console.log("hello")
}
});
$.Myprint();
//写法1
// $.fn.extend({
// GetText:function(){
// for (var i=0;i<this.length;i++) { //写成$(this)也行 (jquery对象)
// console.log(this[i].innerHTML);
// }
// }
// });
//写法2
$.fn.extend({
GetText:function(){
$.each($(this),function(x,y){
console.log(y.innerHTML)
})
}
});
$("p").GetText()
</script>
</body>
八、实例练习
1、正反选
<body> <button onclick="selectAll()">全选</button> <button onclick="cancel()">取消</button> <button onclick="reverse()">反选</button> <hr> <table border="1px"> <tr> <td><input type="checkbox"></td> <td>111</td> <td>111</td> <td>111</td> </tr> <tr> <td><input type="checkbox"></td> <td>222</td> <td>222</td> <td>222</td> </tr> <tr> <td><input type="checkbox"></td> <td>333</td> <td>333</td> <td>333</td> </tr> </table> <script src="jquery-3.4.1.min.js"></script> <script> function selectAll(){ $(":checkbox").each(function(){ $(this).prop("checked",true) }) } function cancel(){ $(":checkbox").each(function(){ $(this).prop("checked",false) }) } function reverse(){ $(":checkbox").each(function(){ if($(this).prop("checked")){ $(this).prop("checked",false) }else{ $(this).prop("checked",true) } }) } </script> </body>
2、模态对话框
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.content{
height: 1800px;
background-color: #5cb85c;
}
.shade{
position: fixed;
top:0;
left:0;
right:0;
bottom:0;
background-color:whitesmoke;
opacity:0.8;
}
.model{
200px;
height:200px;
background-color:darkslateblue ;
position:absolute;
top:50%;
left:50%;
margin-top: -100px;
margin-left:-100px;
}
.hide{
display:none;
}
</style>
</head>
<body>
<div class="content">
<button onclick="show(this)">show</button>
hellohellohellohello
</div>
<div class="shade hide"></div>
<div class="model hide">
<button onclick="cancel(this)">show del</button>
</div>
<script src="jquery-3.4.1.min.js"></script>
<script>
function show(self){
$(self).parent().siblings().removeClass("hide");
}
function cancel(self){
// $(self).parent().addClass("hide");
// $(self).parent().prev().addClass("hide");
$(self).parent().parent().children(".model,.shade").addClass("hide");//写法2
}
</script>
</body>
3、返回顶部
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin:0px;
padding:0px;
}
.div1{
100%;
height:200px;
background-color: red;
overflow: auto;
}
.div2{
100%;
height:1200px;
background-color: blue;
}
.returnTop{
position:fixed;
right:20px;
bottom:20px;
80px;
height:50px;
background-color: darkgrey;
color:white;
text-align: center;
line-height:50px
}
.hide{
display: none;
}
</style>
</head>
<body>
<div class="div1">
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
</div>
<div class="div2">
<button onclick="returnTop2()">return</button>
</div>
<div class="returnTop hide" onclick="returnTop()">返回顶部</div>
<script src="jquery-3.4.1.min.js"></script>
<script>
window.onscroll=function(){
console.log($(window).scrollTop());
if($(window).scrollTop()>100){
$(".returnTop").removeClass("hide");
}else{
$(".returnTop").addClass("hide");
}
};
function returnTop(){
$(window).scrollTop(0);
}
// function returnTop2(){
// $(".div1").scrollTop(0);
// }
//事件绑定。返回的写法2
$(".div2 button").click(function(){
$(".div1").scrollTop(0);
})
</script>
</body>