jQuery
- jQuery是JavaScript库, 创建于2006年的开源项目. jQuery极大的简化了HTML文档操作, 事件处理, 动画和ajax等.
https://www.jquery.com
- 开源
- 轻量级
- 强大的选择器
- 对DOM操作的封装
- 事件处理机制
- 完善的ajax
- 浏览器的兼容
- 链式操作
- 隐式迭代
- 丰富的插件支持
- 完善的文档
<!-- 引入线上的jQuery代码 -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<!-- 引入本地jQuery文件 -->
<script src="./js/jquery-1.12.4.min.js"></script>
$(document).ready()
- 执行时机不同: window.onload在页面机构和资源加载完毕后调用, $(document).ready()在页面结构加载完毕后调用.
- window.onload只能写一个,多了会覆盖; $(document).ready()可以写多个,不会覆盖
- window.onload没有简写; (function(){})
jQuery对象和原生对象
- 原生获取对象,获取的是DOM节点,可以直接使用原生方法.
- 使用jQuery获取的包装之后的对象,只能调用jQuery的方法.
- jQuery对象可以使用[index]或者get(index)转出原生对象, 原生对象使用$()包装成jQuery对象.
var box = document.getElementById('box');
console.log(box);
box.style.background = 'blue';
// $(选择器)可以获取元素
var $box = $('#box');
console.log($box); // n.fn.init [div#box, context: document, selector: "#box"]
console.log($box[0]); // div#box
console.log($box.get(0)); // div#box
$box[0].style.backgroundColor = 'tomato';
$box.get(0).style.backgroundColor = 'orange';
// 原生对象使用$()包装成jQuery对象.
console.log($(box)); // n.fn.init [div#box, context: div#box]
jQuery选择器
- 基本选择器: id选择器, class选择器, 标签选择器
var $li = $('li');
console.log($li);
var $five = $('.five');
console.log($five);
var $six = $('#six');
console.log($six);
$li.css('background', 'orange');
$('.five').css('background', 'blue');
$('#six').css('background', 'red');
$('*').css('background', 'pink');
// window document this 这三个不要加引号
console.log($(window));
console.log($(document));
console.log($(this));
- 层次选择器: 后代选择器, 子元素, 相邻元素, 兄弟元素
$("ul h3").css('background', 'orange'); // 后代选择器
$("ul>h3").css('background', 'red'); // 直接子元素
$('#six+h3').css('background', 'pink'); // 相邻元素
$('#six~h3').css('background', 'tomato'); // 兄弟元素
- 基本过滤器
$('li:first').css('background', 'blue'); // 第一个
$('li:last').css('background', 'blue'); // 最后一个
$('li:lt(3)').css('background', 'red'); // 下标小于3
$('li:gt(3)').css('background', 'red'); // 下标大于3
$('li:eq(3)').css('background', 'blue'); // 下标等于3
var a = 3;
$('li').eq(a).css('background', 'blue'); // 下标等于3
$('li:even').css('background', 'tomato'); // 下标偶数
$('li:odd').css('background', 'blue'); // 下标奇数
$('li:not(.six)').css('background', 'pink'); // 排除类名是six的其余li
- 属性过滤器
$('li').css('background', 'orange');
$("li[title]").css('background', 'orange'); // 具有title属性的li标签
$('li[title=web]').css('color', 'red'); // 具有title属性并且属性值为web的li
$('li[title!=web]').css('color', 'red'); // 选中title属性不是web的li
$('li[title^=w]').css('color', 'red'); // 具有title属性并且是w开头的li
$('li[title$=b]').css('color', 'red'); // 具有title属性并且是b结尾的li
$('li[title*=w]').css('color', 'red'); // 具有title属性并且title属性值包含w的li
- 表单选择器
console.log($(':input')); // input元素
console.log($(':text')); // 单行文本框
console.log($(':password')); // 密码框
console.log($(':radio')); // 单选框
console.log($(':checkbox')); // 多选框
console.log($(':file')); // 文件上传域
console.log($(':submit')); // 文件上传域
console.log($(':reset')); // 重置按钮
jQuery节点
// $('div').children().css('background', 'red'); // 子元素,不考虑后代元素
// $('div').children('p').css('background', 'red'); // 子元素中的p,不考虑后代元素
// $("#li3").next().css('background', 'red'); // 下一个
// $("#li3").nextAll().css('background', 'red'); // 下面所有的兄弟元素
// $("#li3").prev().css('background', 'red'); // 上一个
// $("#li3").prevAll().css('background', 'red'); // 上面所有的兄弟元素
// $('#li3').siblings().css('background', 'red'); // 兄弟元素
// $('#li3').css('background', 'red').siblings().css('background', 'blue');
// var a = 0;
// $('li').eq(a).css('background', 'red').siblings().css('background', 'blue');
// $('div').children('p').css('background', 'red'); // 直接子元素
// $('div').find('*').css('background', 'red'); // 所有后代元素
// $('div').find('p').css('background', 'red'); // 所有后代元素中找p标签
// $('li').filter('.info').css('background', 'red'); // 具有info类名的li
// $('li').not('.info').css('background', 'red'); // 类名不是info的li
属性操作
// 获取属性: jQuery对象.attr(属性名)
// 设置属性: jQuery对象.attr(属性名, 属性值) / jQuery对象.attr(json)
// 删除属性: jQuery对象.removeAttr(属性名)
// console.log($('#box').attr('id'));
// console.log($('#box').attr('class'));
// $('#box').attr('id', 'idbox');
// $('#box').attr({
// id: 'idhaha',
// class: 'classhaha'
// });
// $('#box').removeAttr('class');
// 以下两种情况使用prop()
// 1.当只添加属性名即可生效的属性
// 2.属性值只存在true/false
// $('input').attr('checked', 'checked');
$('input').prop('checked', true);
console.log($('input').prop('checked'));
class操作
// 添加类名: jQuery对象.addClass(类名)
// 删除类名: jQuery对象.removeClass(类名)
// 查找类名: jQuery对象.hasClass(类名) 返回Boolean
// 切换类名: jQuery对象.toggleClass(类名) 有就删除,没有就添加
// is(): 判断是否符合要求
$('#box').addClass('classbox');
$('#box').removeClass('classbox');
console.log($('#box').hasClass('haha'));
console.log($('#box').hasClass('xixi'));
$('#box').toggleClass('haha');
$('#box').toggleClass('haha');
console.log($("#box").is('div'));
console.log($("#box").is('p'));
console.log($("#box").is('#box'));
console.log($("#box").is('.box'));
css操作
// 获取样式: jQuery对象.css(样式名)
// 设置样式: jQuery对象.css(样式名, 样式值) / jQuery对象.css(json)
console.log($('div').css('width')); // 200px
console.log($('div').css('font-size')); // 20px
console.log($('div').css('fontSize')); // 20px
$('div').css('width', '500px');
$('div').css('width', 300);
$('div').css('width', '100');
$('div').css({
width: 300,
height: 300,
background: 'pink',
fontSize: 50
});
操作内容
// 获取内容: jQuery对象.html() / jQuery.text()
// 设置内容: jQuery对象.html(内容) / jQuery.text(内容)
// 区别: html()可以识别标签, text()不可以识别标签
console.log($('div').html());
console.log($('div').text());
$('div').html('<em>这是em标签</em>');
$('div').text('<em>这是em标签</em>');
$.each()
- $.each()可以遍历jQuery对象, 也可以遍历原生的数组和对象.
$.each(arr, function (index, item) {});
// - $.each()可以遍历jQuery对象, 也可以遍历原生的数组和对象.
// - `$.each(arr, function (index, item) {});`
// console.log($('li'));
var s = $.each($('li'), function (index, item) {
console.log(index, item);
});
console.log(s); // $('li')
var arr = [1, 2, 3, 4, 5, 6];
var s = $.each(arr, function (index, item) {
console.log(index, item);
});
console.log(s); // arr
var arr = [
{
name: 'lilei',
age: 20
},
{
name: 'hanmeimei',
age: 21
},
{
name: 'lucy',
age: 22
}
];
$.each(arr, function (index, item) {
console.log(index, item, item.name, item.age);
});
$.map()
- $.map(): 遍历对象, 把处理结果返回给数组
$.map(arr, function () { item, index });
// - $.map(): 遍历对象, 把处理结果返回给数组
// - `$.map(arr, function () { item, index });`
var s = $.map($('li'), function (item, index) {
console.log(index, item);
// return 1;
return item;
});
console.log(s);
var arr = [1, 2, 3, 4, 5, 6];
var s = $.map(arr, function (item, index) {
console.log(index, item);
// return index;
if (item > 3) {
return item;
}
});
console.log(s); // [4, 5, 6]
var arr = [
{
name: 'lilei',
age: 20
},
{
name: 'hanmeimei',
age: 16
},
{
name: 'lucy',
age: 17
}
];
var s = $.map(arr, function (item, index) {
console.log(index, item);
if (item.age >= 18) {
return item;
}
});
console.log(s); // [{name: 'lilei',age: 20}]
$.extend()
- $.extend(): 将一个或多个对象合并到目标对象中
-
$.extend(target, src1, src2...);
将src1,src2…合并到target对象
// - $.extend(): 将一个或多个对象合并到目标对象中
// - `$.extend(target, src1, src2...);` 将src1,src2...合并到target对象
// var target = {
// name: 'lilei'
// };
// var src1 = {
// age: 18
// };
// $.extend(target, src1); // 把src1合并到target, 直接修改了target对象
// console.log(target, src1); // {name: "lilei", age: 18} {age: 18}
// var target = {};
// var src1 = {
// name: 'lilei'
// };
// var src2 = {
// age: 18
// };
// $.extend(target, src1, src2); // 把src1和src2合并到target
// console.log(target, src1, src2); // {name: "lilei", age: 18} {name: "lilei"} {age: 18}
var target = {};
var src = {
name: 'lilei',
age: 18,
gf: {
name: "hanmeimei",
age: 20
}
};
// $.extend(target, src); // 浅拷贝
// src.gf.age = 21;
// console.log(target, src); // { name: 'lilei', age: 18, gf: { name: "hanmeimei", age: 21 } } { name: 'lilei', age: 18, gf: { name: "hanmeimei", age: 21 } }
// 使用$.extend()第一参数为true, 实现深拷贝
$.extend(true, target, src);
src.gf.age = 21;
console.log(target, src); // // { name: 'lilei', age: 18, gf: { name: "hanmeimei", age: 20 } } { name: 'lilei', age: 18, gf: { name: "hanmeimei", age: 21 } }
jQuery中的BOM
元素的宽高
// 获取
console.log($('div').width()); // 200 width
console.log($('div').innerWidth()); // 300 width+padding
console.log($('div').outerWidth()); // 320 width+padding+border
console.log($('div').outerWidth(true)); // 420 width+padding+border+margin
// 设置
$('div').width(300); // width300
$('div').innerWidth(300); // width200 padding50
$('div').outerWidth(300); // width180 padding50 border10
$('div').outerWidth(300, true); // width80 padding50 border10 margin50
// 文档的宽高
console.log($(document).width());
console.log($(document).height());
// 可视区的宽高
console.log($(window).width());
console.log($(window).height());
元素的位置
- jQuery对象.offset(): jQuery对象相对于当前视窗的相对偏移
// jQuery对象.offset(): jQuery对象相对于当前视窗的相对偏移
console.log($('.box1').offset()); // {top: 8, left: 8}
console.log($('.box2').offset()); // {top: 108, left: 108}
console.log($('.box2').offset().left);
console.log($('.box2').offset().top);
滚动条
$(window).scroll(function () {
console.log($(window).scrollTop()); // 滚动时距离顶部的距离
console.log($(window).scrollLeft()); // 滚动时距离左侧的距离
});
DOM操作
创建节点
- 把HTML片段放进$(), 就可以创建对应的节点.
// - 把HTML片段放进$(), 就可以创建对应的节点.
console.log($('<div></div>'));
console.log($('<div>div</div>'));
console.log($('<div class="box">div</div>'));
插入节点
// 新节点.appendTo(目标): 把新节点作为子节点拼接到目标中
$('<div class="box1">box1</div>').appendTo($('body'));
// 目标.append(新节点): 把新节点作为子节点拼接到目标中
$('body').append($('<div class="box2">box2</div>'));
// 新节点.prependTo(目标): 把新节点作为子节点插入到目前中(最前面)
$('<div>box3</div>').prependTo($('body'));
// 目标.prepend(新节点): 把新节点作为子节点插入到目前中(最前面)
$('body').prepend($('<div>box4</div>'));
// 新节点.insertAfter(目标): 把新节点作为兄弟元素插入到目标节点后面
$('<div>box5</div>').insertAfter($('.box1'));
// 目标.after(新节点): 把新节点作为兄弟元素插入到目标节点后面
$('.box1').after($('<div>box6</div>'));
// 新节点.insertBefore(目标): 把新节点作为兄弟元素插入到目标节点前面
$('<div>box7</div>').insertBefore($('.box1'));
// 目标.before(新节点): 把新节点作为兄弟元素插入到目标节点前面
$('.box1').before($('<div>box8</div>'));
删除节点
- jQuery对象.remove(): 删除并返回元素
- jQuery对象.detach(): 删除元素并返回, 保留事件
- jQuery对象.empty(): 清除节点的所有内容(所有额后代元素)
复制节点
- jQuery对象.clone(): 复制节点, 接收一个参数, 参数为Boolean, true表示复制节点和事件, false表示不复制事件
// - jQuery对象.clone(): 复制节点, 接收一个参数, 参数为Boolean, true表示复制节点和事件, false表示不复制事件
$('.box').click(function () {
console.log('click');
});
// $('.box').clone().appendTo($('body')); // 只是复制节点,事件不会复制
$('.box').clone(true).appendTo($('body')); // 复制节点和事件
替换节点
- 被替换的元素.replaceWith(新元素): 使用新元素替换旧元素
- 新元素.replaceAll(被替换的元素): 使用新元素替换旧元素
// - 被替换的元素.replaceWith(新元素): 使用新元素替换旧元素
// - 新元素.replaceAll(被替换的元素): 使用新元素替换旧元素
$('div').replaceWith($('<span>span</span>'));
$('<span>span</span>').replaceAll($('div'));
事件对象
$('.box').click(function (event) {
console.log(event); // 事件对象
console.log(event.originalEvent); // 原生的事件对象
console.log(event.pageX, event.pageY); // 相对于文档的距离
console.log(event.clientX, event.clientY); // 相对于可视区的距离
console.log(event.offsetX, event.offsetY); // 相对于触发事件元素的左上角的距离
console.log(event.screenX, event.screenY); // 相对于屏幕的距离
console.log(event.target); // 事件源
console.log(event.delegateTarget); // 事件绑定的对象
console.log(event.ctrlKey);
console.log(event.shiftKey);
console.log(event.altKey);
event.preventDefault(); // 阻止默认事件
event.stopPropagation(); // 阻止冒泡
return false; // 阻止默认事件+阻止冒泡
});
事件绑定
// 从jQuery1.7开始, 使用 `on()` 替代了 `bind()`, `delegate()`, `live()`. `jQuery对象.on(事件类型, 事件函数)`
// $('div').on('click', function () {
// console.log('click1');
// });
// // 等同于:
// $('div').click(function () {
// console.log('click2');
// });
// 多个事件绑定同一个函数
// $('div').on('click mouseenter', function () {
// console.log('click mouseenter');
// });
// 可以使用对象的形式一次绑定多个事件
// $('div').on({
// click: function () {
// console.log('click');
// },
// mouseenter: function () {
// console.log('mouseenter');
// },
// mouseleave: function () {
// console.log('mouseleave');
// }
// });
// 自定义事件
$('div').on('haha', function () {
console.log('haha');
});
$('div').trigger('haha'); // 触发事件
jQuery事件代理
- 把事件绑定在父元素上, 父元素做代理监听事件, 当子元素触发事件时, 事件默认冒泡给父元素,父元素响应事件, jQuery的事件处理函数中的this就是触发事件的子元素.
jQuery对象.on(事件类型, 子元素, 事件处理函数);
$("ul").on('click', 'li', function () {
// console.log($(this));
$(this).css('background', 'blue');
});
// 后添加的子元素同样可以使用该事件
$('ul').append($('<li>newli</li>'));
事件的取消绑定
// 事件的绑定
$('div').on('click mouseenter', function () {
console.log('click mouseenter');
});
// 事件的取消
$('div').off('mouseenter'); // 取消mouseenter事件
$('div').off(); // 取消所有的事件
事件命名空间
$('div').on('click.zs', function () {
console.log('click--zs');
});
$('div').on('click.ls', function () {
console.log('click--ls');
});
$('div').off('click.zs'); // 取消click.zs,保留click.ls
事件绑定one()
// one(): 绑定的事件只执行一次. jQuery对象.one(事件类型, 事件函数)
$('div').one('click', function () {
console.log('one');
});
// 利用事件的取消实现one效果
$('div').on('click', function () {
console.log('click');
$('div').off();
});
事件合成hover()
// jQuery对象.hover(鼠标进入事件函数, 鼠标离开事件函数); 相当于写了mouseenter和mouseleave事件
$("div").on({
mouseenter: function () {
console.log('mouseenter');
},
mouseleave: function () {
console.log('mouseleave');
}
});
$('div').hover(
function () {
console.log('hover-enter');
},
function () {
console.log('hover-leave');
}
);
jQuery动画
show()显示,
hide()隐藏,
toggle()显示隐藏切换
// jQuery对象.show(speed, easing, callback): 显示元素
// jQuery对象.hide(speed, easing, callback): 隐藏元素
// jQuery对象.toggle(speed, easing, callback): 显示/隐藏切换
// speed: fast(200ms) normal(400ms) slow(600ms) 数字(单位ms)
// easing: swing(开头结尾慢, 中间快) linear(线性匀速)
// callback: 回调函数
$('button').eq(0).click(function () {
$('div').show();
});
$('button').eq(1).click(function () {
$('div').hide();
});
$('button').eq(2).click(function () {
$('div').toggle();
});
$('button').eq(3).click(function () {
$('div').show(1000);
});
$('button').eq(4).click(function () {
$('div').hide(1000);
});
$('button').eq(5).click(function () {
$('div').toggle(1000, function () {
console.log('toggle--done');
});
});
fadeIn()淡入,
fadeOut()淡出,
fadeTo()淡到多少,
fadeToggle() 淡入/淡出切换
// jQuery对象.fadeIn(speed, callback): 淡入
// jQuery对象.fadeOut(speed, callback): 淡出
// jQuery对象.fadeToggle(speed, callback): 淡入/淡出切换
// jQuery对象.fadeTo(speed, 透明度, callback): 淡到多少
$('button').eq(0).click(function () {
$('div').fadeIn();
});
$('button').eq(1).click(function () {
$('div').fadeOut();
});
$('button').eq(2).click(function () {
$('div').fadeToggle();
});
$('button').eq(3).click(function () {
$('div').fadeTo(1000, 0.5);
});
$('button').eq(4).click(function () {
$('div').fadeIn(1000);
});
$('button').eq(5).click(function () {
$('div').fadeOut(1000);
});
$('button').eq(6).click(function () {
$('div').fadeToggle(1000, function () {
console.log('toggle');
});
});
slideDown()下滑展开,
slideUp()上滑收起,
slideToggle() 下滑展开/上滑收起切换
// jQuery对象.slideDown(speed, callback): 下滑展开
// jQuery对象.slideUp(speed, callback): 上滑收起
// jQuery对象.slideToggle(speed, callback): 下滑展开/上滑收起切换
$('button').eq(0).click(function () {
$('div').slideDown();
});
$('button').eq(1).click(function () {
$('div').slideUp();
});
$('button').eq(2).click(function () {
$('div').slideToggle();
});
$('button').eq(3).click(function () {
$('div').slideToggle(1000, function () {
console.log('done');
});
});
animate() 动画
// jQuery对象.animate(动画终点参数json, 动画时间, 运动曲率, 回调函数)
// 动画终点参数json: {left: 300, top: 300}
// 动画时间: 单位ms
// 运动曲率: swing, linear
// 回调函数: 动画完成后调用
// 基本动画: 一次运动一个参数
// $('div').click(function () {
// // $(this).animate({ left: 300 });
// // $(this).animate({ left: 300 }, 2000);
// $(this).animate({ left: 300 }, 2000, 'linear', function () {
// $(this).css('background', 'red');
// });
// });
// 动画累加,累减
// $('div').click(function () {
// $(this).animate({ left: '+=100' }, 2000);
// });
// 多重运动
// $('div').click(function () {
// $(this).animate({ left: 300, top: 500 }, 1000);
// });
// 链式运动
// $('div').click(function () {
// $(this)
// .animate({ left: 500 }, 1000)
// .animate({ top: 500 }, 1000)
// .animate({ left: 0 }, 1000)
// .animate({ top: 0 }, 1000);
// });
// 同一元素动画会排队
$('div').animate({ left: 500 }, 1000);
$('div').animate({ top: 500 }, 1000);
stop() 停止动画, finish()完成动画, delay()延迟动画
$('div')
.delay(1000)
.animate({ left: 500 }, 1000)
.animate({ top: 500 }, 1000)
.animate({ left: 0 }, 1000)
.animate({ top: 50 }, 1000);
// stop(是否清除动画序列, 是否瞬间完成当前动画): 停止动画
$('button').eq(0).click(function () {
$('div').stop(false, false);
});
$('button').eq(1).click(function () {
$('div').stop(false, true);
});
$('button').eq(2).click(function () {
$('div').stop(true, false);
});
$('button').eq(3).click(function () {
$('div').stop(true, true);
});
// finish(): 完成动画
$('button').eq(4).click(function () {
$('div').finish();
});
// delay(): 延迟动画
// is()
$('div').is(':animated')
ajax()
/*
$.ajax({
url: '', // 请求地址
type: '', // 请求类型 get/post, 默认get
cache: 布尔值, // 是否缓存,
data: '', // 参数
dataType: '', // 服务器返回额数据类型 xml,json,html,script,jsonp,text
timeout: '', // 设置超时时间, 单位毫秒
success: function (res) {}, // 成功的回调函数
error: function (err) {}, // 错误的回调函数
complete: function () {} // 完成的回调
});
*/
$.ajax({
url: 'bendi.json',
type: 'get',
success: function (res) {
console.log(res);
console.log(typeof res);
}
});
// $.get()
// $.get(url, 参数, 回调函数);
$.get('bendi.json', function (res) {
console.log(res);
});
// $.post()
// $.post(url, 参数, 回调函数);
$.post('bendi.json', function (res) {
console.log(res);
});