jQuery
jQuery是一个一个优秀的Javascript框架
jQuery 对象就是通过jQuery包装DOM对象后产生的对象。
一、导入方式
<script src="jquery-3.2.1.js"></script>
二、选择标签
- 基本选择器
-
- ID选择器 $("#id的值")
- 类选择器(class) $(".class的值")
- 标签选择器(html标签) $("标签的名字")
- 所有标签 $("*")
-
- 层级选择器
-
- 从一个标签的子子孙孙去找 $("父亲 子子孙孙")
- 从一个标签的儿子里面找 $("父亲>儿子标签")
- 找紧挨着的标签 $("标签+下面紧挨着的那个标签")
- 找后面所有同级的 $("标签~兄弟")
-
- 基本筛选器
$(
"li:first"
)
-
$(
"li:last"
)
$(
"li:eq(2)"
) //索引为2
-
$(
"li:gt(2)"
) //索引大于2
-
$(
"li:lt(2)"
) //索引小于2
$(
"li:even"
) //偶数
-
$(
"li:odd"
) //奇数
$(
"li:focus"
) //焦点
-
$(
"li:not('')"
) //非
- 属性选择器
$(
'[id="div1"]'
)
- 筛选器
- 过滤筛选器
$(
"li"
).eq(2)
$(
"li"
).first()
$(
"ul li"
).hasclass(
"test"
)
- 查找筛选器
-
$("div").children(".test") //儿子 $("div").find(".test") //后代 $(".test").next() $(".test").nextAll() $(".test").nextUntil()//suchas'#d1' $("div").prev() $("div").prevAll() $("div").prevUntil() $(".test").parent() $(".test").parents() $(".test").parentUntil() $("div").siblings() //所有兄弟标签
-
- 过滤筛选器
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>tab</title> <script> function tab(self){ var index=$(self).attr("xxx"); $("#"+index).removeClass("hide").siblings().addClass("hide"); $(self).addClass("current").siblings().removeClass("current"); } </script> <style> *{ margin: 0px; padding: 0px; } .tab_outer{ margin: 0px auto; width: 60%; } .menu{ background-color: #cccccc; /*border: 1px solid red;*/ line-height: 40px; } .menu li{ display: inline-block; } .menu a{ border-right: 1px solid red; padding: 11px; } .content{ background-color: tan; border: 1px solid green; height: 300px; } .hide{ display: none; } .current{ background-color: darkgray; color: yellow; border-top: solid 2px rebeccapurple; } </style> </head> <body> <div class="tab_outer"> <ul class="menu"> <li xxx="c1" class="current" onclick="tab(this);">菜单一</li> <li xxx="c2" onclick="tab(this);">菜单二</li> <li xxx="c3" onclick="tab(this);">菜单三</li> </ul> <div class="content"> <div id="c1">内容一</div> <div id="c2" class="hide">内容二</div> <div id="c3" class="hide">内容三</div> </div> </div> </body> </html>
三、jQuery对象
- 用jQuery选择器查出来的就是jQuery对象
- 只能使用jQuery方法
两者之间转换:
- $(".c1")[0] --> DOM对象
- $(DOM对象)----->jQuery对象
四、对象 属性
--------------------------属性 $("").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")
-------------------循环-------------
- $.each(数组/对象, function(i, v){})
- $("div").each(function(){})
------------CSS类-------------------
- addClass 添加类属性
- removeClass 移除类属性
- toggleClass 开关|切换(有就移除,没有就添加)
prop 获取checkbox是否选中$().prop('checked') 返回布尔值
标签增删改查
//创建一个标签对象 $("<p>") //内部插入 //添加儿子 A.append(B) 吧B添加到A的后面 A.appendTo(B) 吧A添加到B的后面 //当A已是B的元素时,会把A移动到B元素之后 A.prepend(B) 吧B添加到A的前面 A.prependTo(B) 吧A添加到B的前面 //外部插入 //添加兄弟 A.after(B) 吧B添加到A的后面 A.insertAfter(B) 吧A添加到B的后面 A.before(B) 吧B添加到A的前面 A.insertBefore(B) 吧A添加到B的前面 //替换 A.replaceWith(B) --> B替换A A.replaceAll(B) --> A替换B //删除 $("").empty() 内部清空 $("").remove([expr]) 整体都删除 //复制 $("").clone([Even[,deepEven]])
//包裹
A.wrap(B) //B把A包起来
A.unwrap() //不包
A.wrapAll(B) //把A所有元素合到一起,包起来
A.wrap(B) //B把A里的每个元素分别包起来
A.wrap(B) //B把A里的每个元素的内容分别包起来 (里面包)
css操作
CSS
$("").css(“name”)
$("").css("name","sf")
位置
$("").offset([coordinates]) //获取相对窗口的位置
$("").position() //获取相对已经定位的父标签的位置
$("").scrollTop([val]) //滚动条位置
$("").scrollLeft([val])
尺寸
height([val|fn])
- 元素的高度
width([val|fn])
- 元素的宽度
innerHeight()
- 带padding的高度
innerWidth()
- 带padding的宽度
outerHeight([soptions])
- 在innerHeight的基础上再加border的高度
outerWidth([options])
- 在innerHeight的基础上再加border的高度
动画
基本
show([s,[e],[fn]])
hide([s,[e],[fn]]) 可以设置时间,单位毫秒
toggle([s],[e],[fn]) //show|hide间切换, 画面显示的方式 左上<-------->右下
滑动
slideDown([s],[e],[fn])
slideUp([s,[e],[fn]])
slideToggle([s],[e],[fn])
淡入淡出
fadeIn([s],[e],[fn])
fadeOut([s],[e],[fn]) //淡出 时间单位:毫秒
fadeTo([[s],0.66,[e],[fn]])
- 淡出到0.66透明度
fadeToggle([s,[e],[fn]])
- .fadeToggle(3000, function () {
alert("真没用3");
});
自定义
animate(p,[s],[e],[fn])1.8*
- css属性值都可以设置
- 图片变小(漏气)
$(".c6").on("click",function () {
$("img").animate(
{
width:"80px",
height:"80px"
},3000,function () {
//这是一个回调函数
alert(123)
}
)
})
五、事件
1、事件绑定
- $("").on("click", function(){})
- $("").on("click",".btn-warning",function(){}) jQuery的事件委派
2、事件
常用事件
blur([[data],fn]) 失去焦点
focus([[data],fn]) 获取焦点( 搜索框例子)
change([[data],fn]) 当select下拉框中的元素发生改变的时候触发change事件(select例子)
click([[data],fn]) 点击
dblclick([[data],fn]) 双击
scroll([[data],fn]) 滚动
submit([[data],fn]) 提交
不常用事件
error([[data],fn])
focusin([data],fn)
focusout([data],fn)
keydown([[data],fn]) 按下
keypress([[data],fn]) 按键
keyup([[data],fn]) 键松开
mousedown([[data],fn]) 鼠标按下
mouseenter([[data],fn]) 鼠标移进去
mouseleave([[data],fn]) 鼠标离开:只有鼠标离开被选元素的时候,才会触发mouseleave事件
mousemove([[data],fn]) 鼠标移动
mouseout([[data],fn]) 鼠标离开:无论鼠标离开被选元素还是任何子元素,都会触发mouseout事件
mouseover([[data],fn] 鼠标悬停
mouseup([[data],fn]) 鼠标弹起
resize([[data],fn]) 元素窗口发生变化
select([[data],fn])
unload([[data],fn])
补充:
文档树加载完之后绑定事件(绝大多数情况下)
第一种:吧script放在后面。
第二种:
$(document).ready(function(){
// 绑定事件的代码
....
})
简写:
$(function($){
// 绑定事件的代码
....
});

var ele_title = document.getElementsByClassName('title')[0];
var ele_box = document.getElementsByClassName('box')[0];
//鼠标指上去的事件
ele_title.onmouseover = function () {
this.nextElementSibling.classList.remove('hide');
};
//鼠标移走的事件的两种方式
// 方式一(推荐)
ele_box.onmouseleave= function () {
ele_title.nextElementSibling.classList.add('hide');
};

$("button").on("click",function () {
$(window).scrollTop(0);// 给一个滚动条位置
});
$(window).scroll(function () {
//滚动的时候做的操作
if ($(window).scrollTop()>100){
$("button").removeClass("hide")
}
else{
$("button").addClass("hide")
}
});

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="jquery-3.1.1.js"></script> <title>Title</title> <style> *{ margin: 0; padding: 0; } .box{ width: 500px; height: 200px; position: absolute; } .title{ background-color: black; height: 50px; width: 500px; line-height: 50px; text-align: center; color: white; } .content{ width: 500px; height: 150px; background-color: antiquewhite; } </style> <script> $(function () { $(".title").mouseover(function () { $(this).css("cursor","pointer"); }).mousedown(function (e) { var eve = e || window.event; // 原始鼠标横纵坐标位置 var old_m_x=eve.clientX; var old_m_y=eve.clientY; // console.log(old_x); // console.log(old_y); var old_box_y=$(this).parent().offset().top ; var old_box_x=$(this).parent().offset().left ; $(this).bind("mousemove",function (eve) { var new_m_x=eve.clientX; var new_m_y=eve.clientY; var m_x=new_m_x-old_m_x; var m_y=new_m_y-old_m_y; //$(".box").css({"top":old_box_y+m_y+"px","left":old_box_x+m_x+"px"}) var x = old_box_x + m_x; var y = old_box_y + m_y; $(this).parent().css('left',x+'px'); $(this).parent().css('top',y+'px'); }) }) }).mouseout(function(){ $(this).unbind('mousemove'); }) </script> </head> <body> <div class="box"> <div class="title">标题</div> <div class="content">内容</div> </div> </body> </html>
六、jQuery 扩展
$.extend(object) //为JQuery 添加一个静态方法。
$.fn.extend(object) //为JQuery实例添加一个方法。
$.fn.extend({ "print":function(){ for (var i=0;i<this.length;i++){ console.log($(this)[i].innerHTML) } } }); //$("").print()
匿名函数,只想自己用,其他扩展不能用
(function () {
$.extend({
"GDP":function () {
foo();
console.log("带小红花")
}
});
function foo() { 函数的内部可以调用,外部就不可以调用了
console.log("英语八级就是牛")
}
})();
// 如果怕$被别人改,那么就传个参数进去
(function (jq) {
jq.extend({
"GDP":function () {
foo();
console.log("带小红花")
}, //可以扩展多个(加上逗号在写几个)
"SGS":function () {
console.log("你蛤蟆")
}
});
function foo() {
console.log("英语八级就是牛")
}
})(jQuery);
(function (jq) {
jq.fn.extend({
"BJG":function () {
foo2();
console.log("就这样吧")
}
});
function foo2() {
console.log("哎哎呀")
}
})(jQuery);
界面加载完毕后,在执行

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>作业1</title> <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css"> <style> .container { margin-top: 50px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <form action="" novalidate> <div class="form-group"> <label for="username">用户名</label> <input type="text" class="form-control" id="username" placeholder="username"> <span id="helpBlock" class="help-block"></span> </div> <div class="form-group"> <label for="Password">密码</label> <input type="password" class="form-control" id="Password" placeholder="Password"> <span id="helpBlock2" class="help-block"></span> </div> <button type="submit" class="btn btn-default submit">提交</button> </form> </div> </div> </div> <!--jQuery导入一定要放到js的上面--> <script src="jquery-3.1.1.js"></script> <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <script> // var span =$("span"); $(".submit").on("click",function () { //先清空状态 $("form .form-group").removeClass("has-error"); $("form span").text(""); $(":input").each(function () { if ($(this).val().length===0){ var name = $(this).prev().text(); $(this).parent().addClass("has-error"); $(this).next().text(name+"不能为空"); return false } }); return false }) </script> </body> </html>
在这我们看到两个bootstrap文件,
区别:
仅仅是大小不同
so:
大的在测试环境下用,小的在生产环境下用
因为小,用户访问就快
$('#fm').serialize(),获取form表单下所有数据(字典形式)
自定义format功能
<script>
String.prototype.format = function (kwargs) {
var ret = this.replace(/\{(\w+)\}/g,function (km,m) {
return kwargs[m];
});
return ret;
};
var v = "laiying: {age} - {gender}";
var result = v.format({'age':18,'gender': '女'});
console.log(result);
</script>