前端学习之jQuery
jQuery介绍
- jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。
- jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!
- jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程。
jQuery的优点
- 一款轻量级的JS框架。jQuery核心js文件才几十kb,不会影响页面加载速度。
- 丰富的DOM选择器,jQuery的选择器用起来很方便,比如要找到某个DOM对象的相邻元素,JS可能要写好几行代码,而jQuery一行代码就搞定了,再比如要将一个表格的隔行变色,jQuery也是一行代码搞定。
- 链式表达式。jQuery的链式操作可以把多个操作写在一行代码里,更加简洁。
- 事件、样式、动画支持。jQuery还简化了js操作css的代码,并且代码的可读性也比js要强。
- Ajax操作支持。jQuery简化了AJAX操作,后端只需返回一个JSON格式的字符串就能完成与前端的通信。
- 跨浏览器兼容。jQuery基本兼容了现在主流的浏览器,不用再为浏览器的兼容问题而伤透脑筋。
- 插件扩展开发。jQuery有着丰富的第三方的插件,例如:树形菜单、日期控件、图片切换插件、弹出窗口等等基本前端页面上的组件都有对应插件,并且用jQuery插件做出来的效果很炫,并且可以根据自己需要去改写和封装插件,简单实用。
jQuery对象
jQuery对象就是通过jQuery包装DOM对象后产生的对象. jQuery对象是jQuery独有的. 如果一个对象是jQuery对象, 那么它就可以使用jQuery里的方法: $("selector").action().
$("#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()
详情可参考: http://jquery.cuishifeng.cn/
jQuery的选择器和筛选器
选择器
1 基本选择器 $("*") // 选择所有标签对象 $("#id") // id选择器 $(".class") // 类选择器 $("element") // 元素选择器 $(".class,p,div") // 分组选择器 2 层级选择器 $(".class div") // 后代选择器 $(".class>div") // 儿子选择器 $(".class+div") // 毗邻选择器 $(".class~div") //弟弟选择器 3 基本筛选器 $("li:frist") // li标签的第一个 $("li:eq(2)") // li标签索引为2(第3个)的 $("li:even") // li标签索引为偶数的 $("li:gt(1)") //li标签索引大于1的 4 属性选择器 $('[alex]') //含有属性alex的标签 $('[alex="sb"]') //属性alex="sb"的标签 5 表单选择器 $("[type='text']") ==> $(":text") 注意只适用于input标签 $("input:checked")
表单属性选择器
:enabled
:disabled
:checked
:selected
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="">
<input type="checkbox" value="123" checked>
<input type="checkbox" value="456" checked>
<select name="" id="">
<option value="1">Flowers</option>
<option value="2" selected="selected">Gardens</option>
<option value="3" selected="selected">Trees</option>
<option value="3" selected="selected">Trees</option>
</select>
</form>
<script src="jquery-3.3.1.js"></script>
<script>
console.log($("input:checked").length); // 2
console.log($("option:selected").length); // 只能默认选一个, 所以length: 1
$("input:checked").each(function () {
console.log($(this).val()); // 123 456
})
</script>
</body>
</html>
筛选器
过滤筛选器
过滤筛选器 $("li").eq(2) // 索引为2 $("li").first() // 第一个 $("li").last() // 最后一个 $("ul li").hasclass("test") // 判断jQuery对象的class中是否含有"test";
查找筛选器
查找子标签: $("div").children(".test") 查找所有儿子标签
$("div").find(".test") 查找所有后代标签
向下查找兄弟标签: $(".test").next() 查找下一个兄弟标签
$(".test").nextAll() 查找下面的所有兄弟标签
$(".test").nextUntil() 查找下面所有的兄弟标签直到某个为止(不包括这个)
向上查找兄弟标签: $("div").prev() 查找上一个兄弟标签
$("div").prevAll() 查找上面的所有兄弟标签
$("div").prevUntil() 查找上面所有的兄弟标签直到某个为止(不包括这个)
查找所有兄弟标签: $("div").siblings()
查找父标签: $(".test").parent() 查找父标签
$(".test").parents() 查找所有的祖先标签
$(".test").parentUntil() 查找所有的祖先标签直到某个为止(不包括这个)
操作元素(属性, css, 文档处理)
事件
页面加载
页面加载 read(fn) // 当DOM载入就绪可以查询及操纵时绑定一个要执行的函数 $(document).ready(function(){}) ==> $(function(){})
事件绑定
//语法: 标签对象.事件(函数) eg: $("selector").事件(function(){})
事件委派
$("").on(eve,[selector],[data],fn) // 在选择元素上绑定一个或多个事件的事件处理函数。
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<hr>
<button id="add_li">Add_li</button>
<script src="jquery-3.3.1.js"></script>
<script>
// 语法: $("").事件(function(){})
/*$("ul li").click(function () {
alert($(this).html());
});
$("#add_li").click(function () {
$("ul").append("<li>4</li>");
})*/
// 事件委派
$("ul").on("click","li",function () {
alert($(this).html())
});
$("#add_li").click(function () {
$("ul").append("<li>4</li>");
});
事件切换
hover事件:
一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。
over:鼠标移到元素上要触发的函数
out:鼠标移出元素要触发的函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
.test{
width: 200px;
height: 200px;
background-color: wheat;
}
</style>
</head>
<body>
<div class="test"></div>
</body>
<script src="jquery.min.js"></script>
<script>
// function enter(){
// console.log("enter")
// }
// function out(){
// console.log("out")
// }
// $(".test").hover(enter,out)
$(".test").mouseenter(function(){
console.log("enter")
});
$(".test").mouseleave(function(){
console.log("leave")
});
</script>
</html>
属性操作
--------------------------CSS类 $("").addClass(class|fn) $("").removeClass([class|fn]) --------------------------属性 $("").attr(); $("").removeAttr(); $("").prop(); $("").removeProp(); --------------------------HTML代码/文本/值 $("").html([val|fn]) $("").text([val|fn]) $("").val([val|fn|arr]) --------------------------- $("#c1").css({"color":"red","fontSize":"35px"})
<input id="chk1" type="checkbox" />是否可见 <input id="chk2" type="checkbox" checked="checked" />是否可见 <script> //对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。 //对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。 //像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此 //需要使用prop方法去操作才能获得正确的结果。 // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // false // ---------手动选中的时候attr()获得到没有意义的undefined----------- // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // true console.log($("#chk1").prop("checked"));//false console.log($("#chk2").prop("checked"));//true console.log($("#chk1").attr("checked"));//undefined console.log($("#chk2").attr("checked"));//checked </script>
each循环
$("p").css("color", "red")
我们知道上面的代码是将CSS操作加到所有的p标签上, 内部维持一个循环; 但如果对于选中标签进行不同处理, 这时就需要对所有标签数组进行循环遍历.
jQuery支持两种循环方式:
方式一
格式: $.each(obj, fn)
let arr = [10, 20, 30, 40, 50]; $.each(arr, function (i, el) { console.log(i, el) }); let dic={name:"alex",age:"38"}; $.each(dic,function (k,v) { console.log(k,v) })
方式二
格式: $("").each(fn)
$("p").each(function () {
console.log($(this).html())
})
其中, $(this)代指当前循环标签.
each扩展
/* function f(){ /* for(var i=0;i<4;i++){ if (i===2){ return // i=2时, 结束函数执行 } console.log(i); } } f(); */ /* let arr = [10, 20, 30, 40, 50]; $.each(arr, function (i, el) { if (el===30){ return; // 相当于python中的continue } console.log(i, el) }); */ let arr = [10, 20, 30, 40, 50]; $.each(arr, function (i, el) { if (el===30){ return false; // 相当于python中的break } console.log(i, el) }); /* function f(){ /* for(var i=0;i<4;i++){ if (i===2){ return // i=2时, 结束函数执行 } console.log(i); } } f(); */ /* let arr = [10, 20, 30, 40, 50]; $.each(arr, function (i, el) { if (el===30){ return; // 相当于python中的continue } console.log(i, el) }); */ let arr = [10, 20, 30, 40, 50]; $.each(arr, function (i, el) { if (el===30){ return false; // 相当于python中的break } console.log(i, el) });
文档节点处理
//创建一个标签对象 $("<p>") //内部插入 $("").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"); //替换 $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>"); //删除 $("").empty() $("").remove([expr]) //复制 $("").clone([Even[,deepEven]])
动画效果
显示隐藏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#hide").click(function () {
$("p").hide(1000);
});
$("#show").click(function () {
$("p").show(1000);
});
//用于切换被选元素的 hide() 与 show() 方法。
$("#toggle").click(function () {
$("p").toggle();
});
})
</script>
<link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
<p>hello</p>
<button id="hide">隐藏</button>
<button id="show">显示</button>
<button id="toggle">切换</button>
</body>
</html>
滑动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#slideDown").click(function(){
$("#content").slideDown(1000);
});
$("#slideUp").click(function(){
$("#content").slideUp(1000);
});
$("#slideToggle").click(function(){
$("#content").slideToggle(1000);
})
});
</script>
<style>
#content{
text-align: center;
background-color: lightblue;
border:solid 1px red;
display: none;
padding: 50px;
}
</style>
</head>
<body>
<div id="slideDown">出现</div>
<div id="slideUp">隐藏</div>
<div id="slideToggle">toggle</div>
<div id="content">helloworld</div>
</body>
</html>
淡入淡出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#in").click(function(){
$("#id1").fadeIn(1000);
});
$("#out").click(function(){
$("#id1").fadeOut(1000);
});
$("#toggle").click(function(){
$("#id1").fadeToggle(1000);
});
$("#fadeto").click(function(){
$("#id1").fadeTo(1000,0.4);
});
});
</script>
</head>
<body>
<button id="in">fadein</button>
<button id="out">fadeout</button>
<button id="toggle">fadetoggle</button>
<button id="fadeto">fadeto</button>
<div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>
</body>
</html>
回调函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<button>hide</button>
<p>helloworld helloworld helloworld</p>
<script>
$("button").click(function(){
$("p").hide(1000,function(){
alert($(this).html())
})
})
</script>
</body>
</html>
CSS操作
css位置操作
$("").offset([coordinates])
$("").position()
$("").scrollTop([val])
$("").scrollLeft([val])
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.test1{
width: 200px;
height: 200px;
background-color: wheat;
}
</style>
</head>
<body>
<h1>this is offset</h1>
<div class="test1"></div>
<p></p>
<button>change</button>
</body>
<script src="jquery-3.3.1.js"></script>
<script>
var $offset=$(".test1").offset();
var lefts=$offset.left;
var tops=$offset.top;
$("p").text("Top:"+tops+" Left:"+lefts);
$("button").click(function(){
$(".test1").offset({left:200,top:400})
})
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
}
.box1{
width: 200px;
height: 200px;
background-color: rebeccapurple;
}
.box2{
width: 200px;
height: 200px;
background-color: darkcyan;
}
.parent_box{
position: relative;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="parent_box">
<div class="box2"></div>
</div>
<p></p>
<script src="jquery-3.1.1.js"></script>
<script>
var $position=$(".box2").position();
var $left=$position.left;
var $top=$position.top;
$("p").text("TOP:"+$top+"LEFT"+$left)
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.returnTop{
height: 60px;
width: 100px;
background-color: peru;
position: fixed;
right: 0;
bottom: 0;
color: white;
line-height: 60px;
text-align: center;
}
.div1{
background-color: wheat;
font-size: 5px;
overflow: auto;
width: 500px;
height: 200px;
}
.div2{
background-color: darkgrey;
height: 2400px;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div class="div1 div">
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
</div>
<div class="div2 div"></div>
<div class="returnTop hide">返回顶部</div>
<script src="jquery-3.3.1.js"></script>
<script>
$(window).scroll(function(){
var current=$(window).scrollTop();
console.log(current);
if (current>100){
$(".returnTop").removeClass("hide")
}
else {
$(".returnTop").addClass("hide")
}
});
$(".returnTop").click(function(){
$(window).scrollTop(0)
});
</script>
</body>
</html>
尺寸操作
$("").height([val|fn])
$("").width([val|fn])
$("").innerHeight()
$("").innerWidth()
$("").outerHeight([soptions])
$("").outerWidth([options])
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; } .box1{ width: 200px; height: 200px; background-color: wheat; padding: 50px; border: 50px solid rebeccapurple; margin: 50px; } </style> </head> <body> <div class="box1"> DIVDIDVIDIV </div> <p></p> <script src="jquery-3.1.1.js"></script> <script> var $height=$(".box1").height(); var $innerHeight=$(".box1").innerHeight(); var $outerHeight=$(".box1").outerHeight(); var $margin=$(".box1").outerHeight(true); $("p").text($height+"---"+$innerHeight+"-----"+$outerHeight+"-------"+$margin) </script> </body> </html>
扩展方法(插件机制)
jQuery.extend(object)
扩展jQuery对象本身
用来在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元素集来提供新的方法(通常用来制作插件)
增加两个插件的方法:
<body> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <script src="jquery.min.js"></script> <script> jQuery.fn.extend({ check: function() { $(this).attr("checked",true); }, uncheck: function() { $(this).attr("checked",false); } }); $(":checkbox:gt(0)").check() </script> </body>


浙公网安备 33010602011771号