JQ
JQ ~ JS:JQuery和JS可以共存,但是不能混用。
1、模拟css选择网页元素:调用函数$()
//#id
$("#div1").css("backgroundColor", 'red');
//.class
$(".box").css("backgroundColor", 'red');
//tagName
$("ul li").css("backgroundColor", 'blue');
$("[name=hello]").css("backgroundColor", 'yellow');
//表达式的写法
$("li:first").css("backgroundColor", 'red');
$("li:last").css("backgroundColor", 'red');
//比较高级的表达式写法
$("li:even").css("backgroundColor", 'red');
$("li:odd").css("backgroundColor", 'blue');
$("li:eq(2)").css("backgroundColor", 'red');
//多种筛选方式
$("li:eq(2)").css("backgroundColor", 'red');
$("li").eq(2).css("backgroundColor", 'red');
$("li.box").css("backgroundColor", 'blue');
$("li").filter(".box").css("backgroundColor", 'yellow');
2、JQ写法
1 方法函数化 【注】在JQ中基本上见不到等于号。所有的赋值操作都是函数传参的操作。
$(function(){
alert("相当于$(doucment).ready()");
//添加一个点击事件
$("h1").click(function(){
alert("我被点击了");
})
$("h1").mouseover(function(){
this.style.backgroundColor = 'red';
})
$("h1").mouseout(function(){
this.style.backgroundColor = 'blue';
})
});
2 链式操作
$(function () {
//【注】我们可以通过链式操作对上述操作进行简化
$("h1").click(function () {
alert("单击");
})
.css("backgroundColor", 'orange')
.mouseover(function () {
this.style.backgroundColor = 'red';
}).mouseout(function () {
this.style.backgroundColor = 'blue';
})
})
3 取值赋值合体
alert($("#div1").html());
$("#div1").html("<h2>我是新赋值的内容</h2>");
alert($("input").val()); //JQ取值只能去第一个符合条件元素的值
$("input").val("world hello"); //JQ赋值批量操作,会对所有获取到的元素进行赋值。
3、JQ常用方法
.filter( selector )
筛选元素集合中匹配表达式 或 通过传递函数测试的 那些元素集合。
.not( selector )
从匹配的元素集合中移除指定的元素。
.has( selector )
筛选匹配元素集合中的那些有相匹配的选择器或DOM元素的后代元素。
.next( [selector ] )
取得匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。如果提供一个选择器,那么只有紧跟着的兄弟元素满足选择器时,才会返回此元素。
.prev( [selector ] )
取得一个包含匹配的元素集合中每一个元素紧邻的前一个同辈元素的元素集合。选择性筛选的选择器。
.find( selector )
通过一个选择器,jQuery对象,或元素过滤,得到当前匹配的元素集合中每个元素的后代。
.index()
从匹配的元素中搜索给定元素的索引值,从0开始计数。返回值就是jQuery对象中第一个元素相对于它同辈元素的位置。
.eq( index )
减少匹配元素的集合为指定的索引的哪一个元素。提供的索引是从0开始的
attr 设置和修改行间属性
alert($("#div1").attr("id"));
$("#div1").attr("class", 'box22');
//一次性修改多条属性
$("#div1").attr({
title: 'world',
class: "xxxx",
yyy: "zzz"
})
.addClass( className ) .removeClass( [className ] )
$('p').removeClass('myClass noClass').addClass('yourClass');
$(window).width() //returns width of browser viewport
$(document).width(); // returns width of HTML document
.innerWidth() 为匹配的元素集合中获取第一个元素的当前计算宽度值,包括padding,但是不包括border。
.outerWidth( [includeMargin ] ) 获取元素集合中第一个元素的当前计算宽度值,包括padding,border和选择性的margin(True,False)。
// height() innerHeight() outerHeight()
• .insertBefore( target ) 在目标元素前面插入集合中每个匹配的元素(注:插入的元素作为目标元素的兄弟元素)。 .before( content [, content ] )
$('<p>Test</p>').insertBefore('.inner');
• insertAfter(target )
• appendTo(target ) 将匹配的元素插入到目标元素的最后面(注:内部插入)。 appendChild(类似JS的方法)
• prependTo(target ) 将所有元素插入到目标前面(元素内)
• remove( [selector ]) 将匹配元素集合从DOM中删除。(注:同时移除元素上的事件及 jQuery 数据。)
$('.hello').remove(); $('div').remove('.hello');
事件绑定 on off
on 给不同的事件添加不同的函数
$("#div1").on({
click: function () {
alert("点击");
},
mouseover: function () {
$(this).css("backgroundColor", 'orange');
},
mouseout: function () {
$(this).css("backgroundColor", 'blue');
}
})
on 事件委托
// 第二个参数,是触发对象的选择器
$("ul").on("click", "li.box", function(){
$(this).css("backgroundColor", 'red');
})
var i = 6;
$("#btn1").click(function(){
//新增li节点
$(`<li class = 'box'>${i++ * 1111}</li>`).appendTo($("ul"));
})
off 取消事件
$("#cancel").click(function () {
$("#div1").off(); //取消所有事件上的所有函数
$("#div1").off("click"); //取消某一个事件下的所有函数
$("#div1").off("click", show); //取消某一个事件下指定的函数
})
$(window).scrollTop() //输出滚动高度。
$(function () {
$("div").click(function (ev) {
alert(this.id);
// 阻止事件冒泡
ev.stopPropagation();
})
})
$("a").click(function (ev) {
// 阻止默认行为
/* ev.preventDefault();
ev.stopPropagation(); */
//既阻止事件冒泡,又阻止默认行为
return false;
})
which
鼠标事件:button 1 左键 2 滚轮 3 右键
keydown: keyCode 键码 keypress: charCode 字符码
$(document).mousedown(function (ev) {
/* alert(ev.pageX + ", " + ev.pageY); //带滚动距离
alert(ev.clientX + ", " + ev.clientY); //可视窗口为原点 */
alert(ev.which);
})
$(window).keypress(function (ev) {
alert(ev.which);
})
.offset() 在匹配的元素集合中,获取的第一个元素的当前坐标,坐标相对于文档。不算当前元素的margin
.position() 获取匹配元素中第一个元素的当前坐标,相对于offset parent(被定位过的最近祖先)的坐标。算当前元素的margin
.offsetParent() 取得离指定元素最近的含有定位信息的祖先元素。
size() 输出:获取网页元素的个数 alert($('input').size());
$("input").each(function(index, item){
$(item).val(index);
})
4、 特效函数
.hover( handlerIn(eventObject), handlerOut(eventObject) )
将二个事件函数绑定到匹配元素上,分别当鼠标指针进入和离开元素时被执行。
hide() 隐藏 第一个参数:动画持续的毫秒数 第二个参数:回调函数,动画结束的时候执行的
show() 显示 【注】动画效果是,从左上角收起和从左上角展开
slideDown()
slideUp() 【注】 动画效果是卷闸效果。
fadeIn() 淡入
fadeOut() 淡出
fadeTo(动画持续时间, 透明度0~1, 回调函数);
$("#div1").hover(function(){
/* $("#div2").hide(2000, function(){
$("#div1").html("移入")
}); */
/* $("#div2").slideUp(2000, function(){
$("#div1").html("移入")
}); */
/* $("#div2").fadeOut(2000, function(){
$("#div1").html("移入")
}); */
$("#div2").fadeTo(2000, 0.5, function(){
$("#div1").html("移入")
});
}, function(){
/* $("#div2").show(2000, function(){
$("#div1").html("移出")
}); */
/* $("#div2").slideDown(2000, function(){
$("#div1").html("移出")
}); */
/* $("#div2").fadeIn(2000, function(){
$("#div1").html("移出")
}); */
$("#div2").fadeTo(2000, 1, function(){
$("#div1").html("移出")
});
})
5、JQ动画方法animate
.animate( properties [, duration ] [, easing ] [, complete ] )
$("#div1").hover(function(){
$("#div2").stop(true).animate({
width: 300,
height: 300,
opacity: 0.5
}, 4000, function(){
$("#div1").html("移入");
})
}, function(){
$("#div2").stop(true).animate({
width: 200,
height: 200,
opacity: 1
}, 4000, function(){
$("#div1").html("移出");
})
})
6、 更多方法
remove() 删除元素节点 【注】并不会保留这个元素节点上之前的事件和行为
detach() 删除元素节点 【注】会保留这个元素节点上之前的事件和行为
// var node = $("#div1").remove();
var node = $("#div1").detach();
node.appendTo($("#div2"));
$(document).ready() 事件触发在当前的document加载完成以后执行。
JQuery 标签间的内容 html() 相当于innerHTML
JQuery 标签间纯文本 text() 相当于innerText(所有文本)
$("#div1").html("<h1>hello world</h1>"); //会自动解析
$("#div1").text("<h1>hello world</h1>") //不会自动解析
节点操作的方法 【注】下述所有的方法的参数都是选择器
siblings() nextAll() prevAll()
parentsUntil() nextUntil() prevUntil()
parent() 获取父节点
parents() 获取父节点们 参数选择器
closest() 必须传入参数,参数也是选择器,只获取第一个符合条件的元素,从自己开始去查找的
wrap() 每一个获取到的元素节点单独包装
wrapAll() 整体包装
wrapInner() 内部包装
unwrap() 删除包装 删除上面一层包装,不包括body节点
clone() 默认只会克隆节点本身,并不会克隆我们元素节点的行为和事件
clone(true) 既会克隆节点本身,还会克隆元素节点的行为和事件
add() 可以将多个选择器拼接在一起
$("div").add("span").add("ul li")
.css("backgroundColor", 'red')
.click(function(){
alert("单击");
})
.mouseover(function(){
$(this).css("backgroundColor", 'orange');
})
slice() slice(start, end) [start, end)
获取指定范围内获取到的元素节点。
serialize() 将我们表单中的数据拼接成querystring:name1=value1&name2=value2
search ?name1=value1&name2=value2
serializeArray() 将表单数据拼接成数组
$("input").serialize()
ev.target(兼容后触发对象)
ev.type(输出事件类型)
ev.data 配合on使用 传参
trigger() 可以触发官方定义的事件以外, 还可以触发我们自定义的事件
$("#play").on("play", function(){
alert("开始播放音乐");
})
$("#play").on("next", function(){
alert("切换到下一首歌曲");
})
$("button").eq(0).click(function(){
$("#play").trigger("play");
})
$("button").eq(1).click(function(){
$("#play").trigger("next");
})
7、工具方法 $.functionname()
type() 输出当前数据类型 比typeof更加细化
trim() 去掉字符串左右空格
inArray() 查看数组元素的下标,从0开始。 indexOf()
proxy() 功能类似于bind
$.parseJSON() JSON.parse()
noConflict() var qian = $.noConflict(); //给$函数起一个别名 ,主要是防止$被占用
makeArray() 将伪数组转成数组。 Array.from()
8、扩展方法
$.extend() 拓展工具方法 $.xxx() $.yyy()
$.fn.extend() 拓展JQ方法 $().xxx() $().yyy()
$.extend({
aaa: function(){
alert("这是一个工具方法");
}
})
$.fn.extend({
aaa: function(){
alert("这是一个JQ方法");
},
drag: function(){
$(this).mousedown(function(ev){
var offsetX = ev.clientX - $(this).offset().left;
var offsetY = ev.clientY - $(this).offset().top;
var _this = this;
$(document).mousemove(function(ev){
$(_this).css({
left: ev.clientX - offsetX,
top: ev.clientY - offsetY
})
})
})
$(document).mouseup(function(){
$(document).off("mousemove");
})
return this;
}
})
$(function(){
$.aaa();
$("div,p,em").drag()
})
9、cookie单独封装在jquery.cookie.js
$.cookie('the_cookie'); //读取
$.cookie('the_cookiename', 'the_value',[{ 可选项,raw: true value不进行编码, 默认false }]);
$.cookie('the_cookiename',null); //删除cookie
10、ajax
$(function(){
$("#btn1").click(function(){
$.ajax({
type: "get",
url: "https://api.asilu.com/weather/",
data: {
city: "青岛"
},
dataType: "jsonp",//jsonp跨域
success: function(data, statusText){
// alert(data + ", " + statusText);
console.log(data);
},
error: function(msg){
alert(msg);
}
})
})
})
load方法: 将url传入以后,将下载到数据直接填充到被选中元素的innerHTML中
回调函数 data 下载到的数据 statusText 下载的状态 success xhr ajax对象
$("button").eq(0).click(function(){
$("div").load("2.txt #p1", function(data, statusText, xhr){
alert(data + ", " + statusText);
alert(xhr.status);
})
})
$("button").eq(1).click(function(){
$.get("2.txt", function(data, statusText, xhr){
alert(data);
})
})
$("button").eq(2).click(function(){
$.post("1.post.php", {
username: 'tian',
age: 19,
password: "123abc"
}, function(data, statusText, xhr){
alert(data);
})
})