1.选择器
css3语法选择器
$('css3选择器位')
索引匹配
$('div:eq(0)')
$('div').eq(0)
内容
$('div:contains(标签文本内容)') // 注: 采用模糊匹配
2.属性操作
文本
// 赋值: 有参数 $('.box').html('<i>beat box</i>'); // 取值: 无参数 console.log($('.box').text()); // 表单内容 // $('.inp').val("input 内容 为 value"); console.log($('.inp').val());
属性
// 取 console.log($('img').attr('alt')); // 设 $('img').attr('src', 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1611571505,2177664062&fm=26&gp=0.jpg') // 增 $('img').attr('abc', function () { return "ABC"; })
类名
$(this).addClass('active'); // 添加 $(this).removeClass('box'); // 删除 // 如果有active 删除, 反之添加 $(this).toggleClass('active'); // 切换
3.css样式设置
// 取值 console.log($('.box').css('font-size')); // 设值 $('.box').css('color', 'deeppink') // 单一属性设值 .css({ // 设置多个属性值 // 1.就是给css()函数赋值一个js对象 // 2.key为字符串类型,可以省略"",前提要使用js语法,小驼峰命名法 // 2.属性值为数值+单位方式,可以省略单位, 尽量全部用字符串数据赋值 width: '300px', 'height': 300, 'background-color': 'cyan', borderRadius: '30px' }) .css('width', function(index, oldWidth) { // 逻辑单一属性设值 if (index == 0) { // 延迟1s // var b_time = new Date().getTime(); // while (new Date().getTime() - b_time < 1000){} return 1.5 * parseInt(oldWidth); } return oldWidth; })
4.事件
绑定方式
// 第一种 on // 四个参数: 事件名, 委派的子级, {key-value传入的数据}, 事件回调函数 $('.box').on('click', 'span', {name: 'hehe'}, function(ev){}) // 第二种 // 两个参数: {key-value传入的数据}, 事件回调函数 $('.box').click({name: 'hehe'}, function(ev){})
事件对象
// 为jq事件对象, 兼容js事件对象 // 坐标: ev.clientX | ev.clientY // 按键: ev.keyCode // 数据: ev.data.key名 => eg:ev.data.name
冒泡与默认动作
// 冒泡: ev.stopPropagation(); // 默认动作: ev.preventDefault();
委派
$('.box').on('click', 'span', {name: 'hehe'}, function(ev){}) // 注: 通过父级box来绑定点击事件,其实将事件委派给其子级span标签
5.动画
系统预定义
// time_num: 动画持续的时间 // finish_fn: 动画结束后的回调函数 // 1. hide(time_num, finish_fn) | show(time_num, finish_fn) | toggle(time_num, finish_fn) // 2. slideUp() | slideDown() | slideToggle() 参数同上 // 3.fadeOut() | fadeIn() | fadeTo() | fadeToggle() 参数同上
自定义动画
// 参数: 做动画的样式们 {}, 动画持续时间, 运动曲线, 动画结束后的回调函数 animate({ width: 300, height: 500 }, 300, 'linear', function() { // 动画结束后回调 }) // 动画本体采用的是css动画