jQuery

jQuery

一、jQuery介绍

  • JavaScript类库(js文件)
  • 封装了很多简单易用的方法(浏览器兼容)
  • 绝大多数用来简化DOM操作
  • 提升开发效率

1. 选择器

jQuery中通过选择器来获取DOM节点,功能类型与原生的querySelectorAll方法,支持的选择器与CSS的选择器几乎一致

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>jQuery 选择器</title>
    <style>
      body {
        padding: 0 30px;
      }

      p {
        color: #333;
      }
    </style>
  </head>
  <body>
    <h3>04-jQuery <span>选择器</span></h3>
    <p>
      jQuery 中的选择器是用来获取 DOM 节点的,其功能类似于原生的
      querySelectorAll 方法,jQuery 中所支持的选择器与 CSS 的选择器几乎一致。
    </p>
    <p>jQuery 封装了大量 DOM 操作的方法,极大的提升了开发效率!</p>
    <p class="p">jQuery 的口号是 <span>Write Less Do More!</span></p>
    <p id="p">jQuery 内部对浏览器之间的兼容也做了相关的处理。</p>
    <!-- 导入 jQuery -->
    <script src="./jquery/jquery-3.5.1.js"></script>
    <script>
      // 1. 标签选择器
      $('p').css('backgroundColor','pink')
      // 2. 类选择器
     $('.p').css('backgroundColor','skyblue')
      // 3. id选择器
     $('#p').css('backgroundColor','orange')
      // 4. 后代选择器
      $('p span').css('backgroundColor','red')
    </script>
  </body>
</html>

2. jQuery对象

jQuery中利用选择器获取到并非原生的DOM对象,而是jQuery对象

语法:

 // 1. 打印dom和jQ对象的区别
      let li = document.querySelector('li')
      console.log(li);
      let $li = $('li')
      console.log($li);
      // 2. jQ对象的方法
     $li.css('backgroundColor','hotpink')

      // 3. 混着用(只是测试而已)
      // li.css('backgroundColor', 'skyblue')

      // 4. dom对象转jQ对象
     let $li2 = $(li)
     $li2.css('backgroundColor','skyblue')

jQuery对象和DOM对象的语法不同混用

3. 事件绑定

在jQuery中以原生事件类型的名称为依据,封装了相对应的事件处理方法

语法:

$('选择器').click(function () {
    // 逻辑...
})
 // 1.为 li 添加点击事件
     $('li').click(function () {
      console.log('click');
      console.log(this);
      let $this = $(this)
      $this.css('backgroundColor','pink')
     })

      // 2.为 .text 添加获得焦点事件
     $('.text').focus(function () {
      console.log('focus');
     })

      // 3.为 .text 添加失去焦点事件
     $('.text').blur(function () {
      console.log('blur');
     })

      // 4.为 .box 添加鼠标移入事件
      $('.box').mouseenter(function () {
        console.log('mouseenter');
        $(this).css('backgroundColor','pink')
      })

      // 5.为 .box 添加鼠标移出事件
      $('.box').mouseleave(function () {
        console.log('mouseleave');
        $(this).css('backgroundColor','yellowgreen')
      })

4. 链式编程

链式编程通过点(.)把多个操作(方法)连续的写下去,形式和链子一样的结构

语法:

$('.text').foucs(回调函数).blur(回调函数).change(回调函数)
// 2. 使用链式编程一次性绑定 获得焦点 失去焦点 内容改变事件
      $('.text')
      .focus(function() {
        console.log('获得焦点');
      })
      .blur(function() {
        console.log('失去焦点');
      })
      .change(function() {
        console.log('内容改变');
      })
// 3. 测试jQuery方法的返回值
       let $test = $('.test')
       let $test2 = $test.focus(function () {
         console.log('获得焦点')
       })

       console.log($test === $test2)

二、jQuery常用API

1. 内容操纵

jQuery中封装了设置和读取率网页元素文本内容的方法

语法:

// 设置
$('选择器').html('内容')
$('选择器').text('内容')
// 读取
$('选择器').html()
$('选择器').text()
 //  1. 设置普通文本
       $('.box1').html('黑马程序员')
       $('.box2').text('黑马程序员')

      // 2. 设置标签
      $('.box1').html('<a href="#">黑马程序员</a>')
      $('.box2').text('<a href="#">黑马程序员</a>')

      // 3. 取值
      let boxHtml = $('.box1').html()
      let boxText = $('.box1').text()
      console.log(boxHtml);
      console.log(boxText);
      // 4. 链式编程
      let $box = $('.box1')
      $box.html('<a href="#">传智教育</a>').click(function(){
        console.log('黑马程序员');
      })
  • 设置时:html方法解析标签,text不解析标签
  • 取值时:html方法获取标签,text只获取文本
  • 有一种使用方式支持链式编程

2. 计数器

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>计数器</title>
    <link rel="stylesheet" href="./css/index.css" />
  </head>

  <body>
    <!-- html结构 -->
    <div id="app">
      <!-- 计数器功能区域 -->
      <div class="input-num">
        <!-- 减号 -->
        <button>
          -
        </button>
        <!-- 内容 -->
        <span>0</span>
        <!-- 加号 -->
        <button>
          +
        </button>
      </div>
      <img src="http://www.itheima.com/images/logo.png" alt="" />
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="./jquery/jquery-3.5.1.js"></script>
    <!-- 编码 -->
    <script>
      // 递减
     $('.input-num button:first-child').click(function() {
     // console.log('递减');
     let num = $('.input-num span').text()
     if(num > 0){
      num--
      $('.input-num span').text(num)
     } else {
      alert('别点了,到底了!')
      return
     }
     })
      // 累加
     $('.input-num button:last-child').click(function() {
     // console.log('累加');
     let num = $('.input-num span').text()
     if(num < 10) {
      num++
      $('.input-num span').text(num)
     } else {
      alert('别点了,到顶了')
      return
     }
     })
    </script>
  </body>
</html>

3. 过滤方法

jQuery中封装了过滤方法,对jQuery对象中的dom元素再次筛选

// 匹配的第一个元素
.first()
// 匹配的最后一个元素
.last()
// 根据索引匹配
.eq(索引)

注意:

  1. eq方法的索引从0开始
  2. 返回的是jQuery对象

4. 样式操纵

jQuery中对样式的操作进行封装,可以设置或者获取样式

// 1. 键值对设置
.css('样式名','值')
.css('backgroundCOlor','pink')
.css('color','red')
.css('width','200px')
.css('height','200')
  • 数值类的样式省略单位,默认会使用px

  • 获取样式需要传递样式名

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>11-样式操纵</title>
    <style>
      body {
        padding: 0 30px;
      }

      p {
        color: #333;
      }
      div {
        width: 200px;
        height: 200px;
        margin-top: 20px;
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <h3>11-样式操纵</h3>
    <p>css可以获取及设置元素样式,设置的是行内样式</p>
    <!-- 测试用的盒子 -->
    <div class="box"></div>
    <!-- 引入 jQuery -->
    <script src="./jquery/jquery-3.5.1.js"></script>
    <script>
      // 1. 键值对设置
     $('.box').css('backgroundColor','pink')
     $('.box').css('border','10px solid orange')
     $('.box').css('width',250)
     $('.box').css('height',250)
      // 2. 对象方式设置
      $('.box').css({
        backgroundColor: 'skyblue',
        border: '10px solid yellowgreen',
        width: 100,
        height: 100
      })

      // 3. 样式获取
     let width = $('.box').css('width')
     console.log(width);
    </script>
  </body>
</html>

5. 属性操纵

jQuery中对属性的操作进行封装,可以设置、获取和删除属性

语法:

// 1.赋值
.attr('属性名','值')
// 2. 取值
.attr('属性名')
// 3. 删除属性
.removeAttr('属性名')
 // 1. 赋值
      $('a').attr('href','http://www.itheima.com')
      $('img').attr('src','http://www.itheima.com/images/logo.png')
      $('img').attr('info', '黑马程序员')
      // 2. 取值
      let href = $('a').attr('href')
      console.log('href:', href)
      let info = $('img').attr('info')
      console.log('info:', info)
      // 3. 删除
     $('a').removeAttr('href')
     $('img').removeAttr('src')
     $('img').removeAttr('info')

6.图片切换

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>图片切换</title>
    <link rel="stylesheet" href="./css/index.css" />
  </head>

  <body>
    <div id="mask">
      <div class="center">
        <!-- 顶部logo -->
        <h2 class="title">
          <img src="./images/logo.png" alt="" />
        </h2>
        <!-- 图片 -->
        <img class="cover" src="./images/1.png" alt="" />
        <!-- 左箭头 -->
        <a href="javascript:void(0)" class="left">
          <img src="./images/prev.png" alt="" />
        </a>
        <!-- 右箭头 -->
        <a href="javascript:void(0)" class="right">
          <img src="./images/next.png" alt="" />
        </a>
      </div>
    </div>
    <!-- 导入jQuery -->
    <script src="./jquery/jquery-3.5.1.min.js"></script>
    <script>
      // 1.箭头缩放
      $('.center a')
      .mouseenter(function() {
        $(this).css('transform','scale(1.1')
      })
      .mouseleave(function() {
        $(this).css('transform','scale(1)')
      })
      // 2. 图片切换
      $('.left').css('display','none')
      let index = 1
      $('.right').click(function() {
        index++
        $('.cover').attr('src',`./images/${index}.png`)
        if(index === 5){
          $(this).css('display','none')
        }
        $('.left').css('display','block')
      })
      $('.left').click(function() {
        index--
        $('.cover').attr('src',`./images/${index}.png`)
        if(index === 1) {
          $(this).css('display','none')
        }
        $('.right').css('display','block')
      })
    </script>
  </body>
</html>

7. 操纵value

jQuery中封装了操纵表单元素value属性的方法,可以取值和赋值

语法:

// 1. 赋值
.val('参数')
// 2. 取值
.val()
 // 1. 赋值
      $('.text').val('黑马程序员')
      // 2. 取值
      $('.text').blur(function() {
        let value = $(this).val()
        console.log(value);
      })

8. 查找方法

jQuery中封装了查找元素的方法,可以基于元素的结构关系查找新的元素

//1.父元素
.parent()
//2.子元素
.children('选择器')
//3.兄弟元素
.siblings('选择器')
//4.后代元素
.find('选择器')
   // 1. 父元素 parent
      $('.course')
      .parent()
      .css('backgroundColor','pink')

      // 2. 子元素 children
      $('.course')
      .children()
      .css('backgroundColor','skyblue')
      $('.campus')
      .children('.bj')
      .css('backgroundColor','pink')

      // 3.  兄弟元素 siblings
      $('.sh')
      .siblings()
      .css('color','red')
      $('.sh')
      .siblings('.sz')
      .css('backgroundColor','yellowgreen')

      // 4. 后代元素 find
      $('.container')
      .find('h4')
      .css('backgroundColor','yellowgreen')
      $('.container')
      .find('li')
      .css('border','10px solid orange')
  • find方法 方法需要传入选择器
  • children,sibings方法支持传入选择器

9. 操纵类名

jQuery中封装了为网页元素添加、移除、检测、切换类名的方法

语法:

//1.添加类名
.addClass('类名')
//2.移除类名
.removeClass('类名')
//3.判断类名 返回布尔值
.hasClass('类名')
// 1.  添加类名
     $('.add').click(function() {
      $('.test').addClass('active')
     })

      // 2. 移除类名
     $('.remove').click(function() {
      $('.test').removeClass('active')
     })

      // 3. 判断类名
     $('.has').click(function() {
     let res = $('.test').hasClass('active')
      console.log('red:',res);
     })

      // 4. 切换类名
    $('.toggle').click(function() {
      $('.test').toggleClass('active')
    })

10. 事件进阶

jQuery封装了更多灵活的on /off、one方法处理DOM事件

//1.注册事件
.on('事件名',function(){
    
})
//2.移除指定事件
.off('事件名')
//3.移除所有事件
.off()
//4.组成一次性事件
.one('事件名',function(){
    
})
 // 1. 注册事件 on
     $('.onoff').on('focus',function(){
      console.log('获取焦点');
     })
     .on('blur',function() {
      console.log('失去焦点');
     })
     .on('input',function() {
      let value = $(this).val()
      console.log('value:',value);
     })
      // 2. 移除指定事件 off
        $('.onoff').off('input')
      // 3. 移除所有事件 off
        $('.onoff').off()
      // 4. 注册一次性事件 one
        $('.one').one('click',function(){
          alert('支付成功!')
        })
  • on,one方法回调函数中的this是触发事件的dom元素

三、综合案例(输入统计)

// 1. 高亮效果
      $('.input-box textarea')
      .focus(function() {
        $(this)
        .parent()
        .addClass('actived')
      })
      .blur(function() {
        $(this)
        .parent()
        .removeClass('actived')
      })
      //2. 字数统计
      $('.input-box textarea').on('input',function() {
       // $('.words span').html(($(this).val()).length)
       // 优化
       let length = $(this).val().length
        $('.words span').text(length)
       if(length === 0){
        $('.publish_btn').addClass('disabled')
       } else {
        $('.publish_btn').removeClass('disabled')
       }
      })
      // 3. 发布微博
      $('.publish_btn').click(function() {
        let length = $('.input-box textarea').val().length
         if(length === 0){
          alert('发布内容不能为空!')
          return
         }      
        $('.words span').html(0)
        $('.input-box textarea').val('')
        $('.publish_btn').addClass('disabled')
        
      })

四、登陆切换案例

1. 触发事件

jQuery中如何通过代码的方式触发绑定事件

//1.直接触发
.事件名()
//2.trigger触发
.trigger('事件名')
//3.触发自定义事件
.trigger('自定义事件')
//4.注册自定义事件
.on('自定义事件',function(){})
// 1. 直接触发
      $('.btn').click(function(){
        $(this).css('backgroundColor','skyblue')
      })
      $('.text').on('input',function(){
        console.log('input触发了');
      })
      // 2. trigger触发
      $('.btn').trigger('click')
      $('.text').trigger('.input')
      // 3. 注册自定义事件
      $('.text').on('it-input',function() {
        console.log('自定义事件触发了');
      })

      // 4. 触发自定义事件
      $('.text').trigger('it-input')

2. 登陆切换案例

// 账号登录 安全登录切换
     $('.label').click(function() {
      $(this).addClass('active')
      $(this).siblings().removeClass('active')
      let id = $(this).attr('data-label')
      $(id).css('display','block')
      $(id).siblings().css('display','none')
     })
      // 图标 和 安全登录切换
     $('.icon').click(function() {
      let isActive = $(this).hasClass('active')
      if(isActive){
        $('.label').last().click()
      } else {
        $(this).addClass('active').siblings().removeClass('active')
        let label = $(this).attr('data-label')
        $(label).css('display','block').siblings().css('display','none')
      }
     })

3. Window事件绑定

使用jQuery为Window对象绑定事件

//滚动
$(window).scroll(function() {
    
})
//点击
$(window).click(function() {
    
})

五、jQuery动画

1. 获取位置

通过jQuery直接获取元素的位置

//取值
$('选择器').offset()
//取值
$('选择器').position()
//返回值
{top:126,left:58}
  • 参照物不同
  1. offset参照html标签
  2. position参照离他最近有定位的祖先元素
  • margin
  1. offset会把外边距margin计算进去
  2. position以外边距margin为边界,不计算margin

2. 滚动距离

通过jQuery获取元素的滚动距离

语法:

// 取值
$('选择器').scrollLeft()
$('选择器').scrollTop()
// 赋值
$('选择器').scrollLeft()
$('选择器').scrollTop()
 // 1.获取 页面 滚动距离
     $('.html-get').click(function() {
      let top = $('html').scrollTop()
      console.log('top:',top);
      let left = $('html').scrollLeft()
      console.log('left:',left);
     })

      // 2.设置 页面 滚动距离
     $('.html-set').click(function() {
      $('html').scrollTop(100)
      $('html').scrollLeft(100)
     })

      // 3.获取 box 滚动距离
      $('.box-get').click(function() {
        let top = $('.box').scrollTop()
        console.log('top:',top);
        let left = $('.box').scrollLeft()
        console.log('left:',left);
      })
      // 4.设置 box 滚动距离
     $('.box-set').click(function() {
      $('.box').scrollTop(100)
      $('.box').scrollLeft(100)
     })

3.显示&隐藏动画

通过jQuery以动画的方式切换元素的显示&隐藏

语法:

//显示
$('选择器').show(持续时间)
//隐藏
$('选择器').hide(持续时间)
//显示*隐藏
$('选择器').toggle(持续时间)
<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>05-显示&隐藏动画</title>
    <style>
      body {
        padding: 0 30px;
      }

      p {
        color: #333;
      }

      .box {
        width: 200px;
        height: 100px;
        margin-top: 20px;
        background-color: yellowgreen;
      }
    </style>
  </head>
  <body>
    <h3>显示&隐藏</h3>
    <p>jQuery 中封装了元素显示/隐藏的快捷操作,并且支持动画形式的交互效果。</p>

    <button class="show">显示</button>
    <button class="hide">隐藏</button>
    <button class="toggle">显示&隐藏</button>

    <div class="box"></div>

    <script src="./jquery/jquery-3.5.1.min.js"></script>
    <script>
      // 1.show方法
     $('.show').click(function() {
      $('.box').show(1000)
     })
      // 2.hide方法
     $('.hide').click(function() {
      $('.box').hide(1000)
     })
      // 3.toggle方法
     $('.toggle').click(function() {
      $('.box').toggle(2000)
     })      
    </script>
  </body>
</html>

4. 淡入&淡出动画

通过jQuery以淡入&淡出的方式切换元素的显示隐藏

语法:

//淡入
$('选择器').fadeIn(持续时间)
//淡出
$('选择器').fadeOut(持续时间)
//淡入&淡出
$('选择器').fadeToggle(持续时间)
 // 1.fadeIn 淡入
      $('.fade-in').click(function() {
        $('.box').fadeIn(2000)
      })
      // 2.fadeOut 淡出
      $('.fade-out').click(function() {
        $('.box').fadeOut(2000)
      })

      // 3.fadeToggle 淡入&淡出
      $('.fade-toggle').click(function() {
        $('.box').fadeToggle(2000)
      })
  • 毫秒为单位

5. 展开&收起动画

通过jQuery以展开(高度增加-显示)&收起(高度减少-隐藏)的方式切换元素的显示隐藏

语法:

//展开
$('选择器').slideDown(持续时间)
//收起
$('选择器').slideUp(持续时间)
//展开&收起
$('选择器').slideToggle(持续时间)
 // 1.slideDown展开
     $('.slide-down').click(function() {
      $('.box').slideDown(3000)
     })

      // 2.slideUp收起
      $('.slide-up').click(function() {
        $('.box').slideUp(3000)
      })
      // 3.slideToggle展开&收起
     $('.slide-toggle').click(function() {
      $('.box').slideToggle(3000)
     })
  • 毫秒为单位

6. 动画队列及停止方法

通过jQuery为元素设置的多个动画会依次添加到动画队列中,并根据添加的顺序依次播放

语法:

//停止当前动画
$('选择器').stop()
//清空队列,在动画当前状态停止
$('选择器').stop(true)
//清空队列直接到当前动画的结束状态
$('选择器').stop(true,true)
 // 1.添加动画
     $('.add').click(function() {
      $('.box')
      .slideUp(4000)
      .slideDown(4000)
      .hide(4000)
      .show(4000)
     })
      // 2.不传递参数 stop()
     $('.stop').click(function() {
      $('.box').stop()
     })
      // 3.传递1个true stop(true)
     $('.stop2').click(function() {
      $('.box').stop(true)
     })
      // 4.传递2个true stop(true,true)
     $('.stop3').click(function() {
      $('.box').stop(true,true)
     })
  • 动画方法和stop方法返回的是同一个jQuery对象(链式编程)

7.自定义动画

jQuery提供了animate方法来实现更为复杂的动画效果

语法:

$('选择器').animate(动画属性,持续时间)
 $('.gotop').click(function() {
        $('html').animate({
          scrollTop: 0
        })
      })
  • 注意:
  1. 数值类样式支持动画,支持多个
  2. 默认单位是px
  3. 支持非样式的特殊属性

六、综合案例(爱旅行)

1. 插入节点

jQuery中封装了在指定位置动态插入元素节点的方法,可以插入节点或者改变节点位置

语法:

//4个方法参数一样  位置不同
$('父元素选择器').append(参数) // 父元素结尾
$('父元素选择器').prepend(参数) // 父元素开头
$('兄弟元素选择器').before(参数) // 兄弟元素前面
$('兄弟元素选择器').after(参数) // 兄弟元后面
 // 1.父元素结尾插入节点
     $('.insert .append').click(function() {
      // html结构
      $('.container').append('<img src="./img/旺财.jpg" alt="">')
     })

      // 2.父元素开头插入节点
      $('.insert .prepend').click(function () {
        // html结构
        $('.container').prepend('<img src="./img/旺财.jpg" alt="">')
      })

      // 3.兄弟元素前插入节点
      $('.insert .before').click(function () {
        // html结构
        $('.Teemo').before('<img src="./img/旺财.jpg" alt="">')
      })

      // 4.兄弟元素后插入节点
      $('.insert .after').click(function () {
        // html结构
        $('.Teemo').after('<img src="./img/旺财.jpg" alt="">')
      })

      // 5.移动到父元素结尾
      $('.move .append').click(function () {
        // dom元素
        // $('.container').append(document.querySelector('.doge'))
        // jQuery对象
        $('.container').append($('.doge'))
      })
      // 6.移动到父元素开头
      $('.move .prepend').click(function () {
        // jQuery对象
        $('.container').prepend($('.doge'))
      })

      // 7.移动到兄弟元素前面
      $('.move .before').click(function () {
        // jQuery对象
        $('.Teemo').before($('.doge'))
      })

      // 8.移动到兄弟元素后面
      $('.move .after').click(function () {
        // jQuery对象
        $('.Teemo').after($('.doge'))
      })
  • 插入节点:传入创建的dom元素或者html结构

  • 改变位置:传入现有的dom元素或者jQuery对象

2. 动画回调函数

所有的jQuery动画方法都支持传入的回调函数

语法:

$('选择器').基础动画方法(回调函数)
$('选择器').基础动画方法(持续时间,回调函数)
$('选择器').animate(属性,回调函数)
$('选择器').animate(属性,持续时间,回调函数)
// 1.简单动画的回调函数
      $('.simple').click(function() {
        $('.box').fadeOut(2000,function() {
          console.log('淡出了');
          console.log('this:',this);
        })
      })
      // 2.自定义动画的回调函数
      $('.animate').click(function() {
        $('.box').animate({
          width:300,
          height:200
        },function() {
          console.log('变大了');
          console.log('this:',this);
          $(this).css({
            backgroundColor:'pink'
          })
        })
      })
  • 回调函数会在动画执行完毕时立刻执行
  • 回调函数中的this是执行动画的dom元素

3. 动画的延迟方法

jQuery不仅可以设置动画执行的高度,还能在动画执行前设置一定的延时

语法:

$('选择器').delay(延迟时间).动画方法()
 $('.animate').click(function () {
        $('.box')
            .delay(2000)
            .fadeOut()
            .delay(2000)
            .slideDown()
    })

4. 获取高度

jQuery对获取元素尺寸进行了封装,使得在不同场景中获取元素尺寸十分方便

语法:

$('选择器').width() // 内容宽度
$('选择器').height() // 内容高度
$('选择器').innerWidth() // 内容宽度 + 内边距
$('选择器').innerHeight() // 内容高度 + 内边距
$('选择器').outerWidth() // 内容宽度 + 内边距 + 边框
$('选择器').outerHeight() // 内容高度 + 内边距 + 边框
$('选择器').outerWidth(true)// 内容宽度 + 内边距 + 边框 + 外边距
$('选择器').outerHeight(true)//内容高度 + 内边距 + 边框 + 外边距
// 1.获取元素内容区域大小
    $('.content').click(function () {
        let width = $('.box').width()
        let height = $('.box').height()
        console.log('width:',width)
        console.log('height:',height)
    })
    // 2.获取元素内容区域 + 内边距大小
    $('.padding').click(function () {
        let width = $('.box').innerWidth()
        let height = $('.box').innerHeight()
        console.log('innerWidth:',width)
        console.log('innerHeight:',height)
    })
    // 3.获取元素内容区域 + 内边距 + 边框大小
    $('.border').click(function () {
        let width = $('.box').outerWidth()
        let height = $('.box').outerHeight()
        console.log('outerWidth:',width)
        console.log('outerHeight:',height)
    })
    // 4.获取元素内容区域 + 内边距 + 边框 + 外边距大小
    $('.margin').click(function () {
        let width = $('.box').outerWidth(true)
        let height = $('.box').outerHeight(true)
        console.log('outerWidth(true):',width)
        console.log('outerHeight(true):',height)
    })

七、事件委托和Notebook案例

1. 事件参数

jQuery绑定的事件中可以获取事件参数(事件对象),用法和原生JS完全一致

语法:

//没定义事件参数
$('选择器').事件(function(){
    
})
//定义了事件参数
$('选择器').事件(function(e){
    e.stopPropagation()
})
 // 1. 事件触发对象
     $('.outer').click(function(e) {
      console.log('outer-click');
     })
      // 2. 阻止冒泡
    $('.box').click(function(e) {
      console.log('outer-click');
      e.stopPropagation()
    })
      // 3. 阻止默认行为
    $('a').click(function(e){
      e.preventDefault()
    })
      // 4. 判断键盘按键
    $('input').keyup(function(e) {
      console.log(e.keyCode);
      if(e.keyCode === 13) {
        alert('您按下了回车')
      }
    })
  • jQuery已经处理了事件参数和兼容性

2. 删除节点

jQuery中封装了动态删除元素节点的方法

语法:

jQuery对象.remove()
 // 1.删除自己
      $('.remove').click(function() {
        $(this).remove()
      })
      // 2.删除父元素
     $('.remove-box').click(function() {
      $(this).parent().remove()
     })
  • remove方法删除的是调用方法的元素节点

3.事件委托

jQuery中封装了事件委托的支持,直接通过on方法即可使用

语法:

//直接绑定
$('选择器').on('事件名',function9{})
//事件委托
$('祖先选择器').on('事件名','后代选择器',function() {})
 $('.box').on('click','.dog',function() {
      $(this).remove()
     })
      // 2.新增后代元素的事件绑定
    $('.add').click(function() {
      $('.box').append(`<img class = "doge" src = "./img/旺财2.jpg" alt = "">`)
    })
    $('.box').on('click','.dege',function() {
      $(this).remove()
    })
      // 3.原理是事件冒泡
    $('.dog').click(e => {
      e.stopPropagation()
    })      
  • 减少时间注册
  • 解决动态增加后代元素的时间绑定问题
  • 原理是事件冒泡
  • 回到函数中的this是触发事件的dom对象
4. 综合案例(记事本)
;(function () {
  //1. 新增
  $('#addTodo').keyup(function(e){
    // 判断
    if(e.keyCode === 13) {
      let value = $(this).val()
      if(value !== '') {
        $('#todoList').append(`
        <li style = "display : none">
            <div class="view">
              <label>${value}</label>
              <button class="destroy"></button>
            </div>
          </li>
        `)
        $('#todoList li').last().slideDown(function() {
          count()
        })
      }
      $(this).val('')
    }
  })
  //2. 删除
  $('#todoList').on('click','.destroy',function() {
    let $li = $(this).parent().parent()
    $li.fadeOut(function(){
      $(this).remove()
      count()
    })
  })
  //3. 统计条数
  function count () {
    $('.todo-count strong').html($('#todoList li').length)
  }
})()

八、jQuery常用插件

1. 入口函数

jQuery中提供了更为简便的入口函数写法

语法:

// 原生写法:
window.onload = function() {
    
}
//JQ写法:
$(window).on('load',function(){
    
})
  • 页面资源加载完毕执行(包括图片、css等等)逻辑代码
// 完整写法
$(document).ready(function(){
    
})
// 简化写法
$(function(){
    
})
  • DOM载入完毕就会执行
// 0. 直接修改背景色(错误演示)
       $('.box').css('backgroundColor','orange')

      // 1. onload原始写法
       window.addEventListener('load',() => {
         $('.box').css('backgroundColor','orange')
       })

      // 2. onload结合jQ
       $(window).on('load',function(){
         $('.box').css('backgroundColor','pink')
       })

       //3. ready完整写法
         $(document).ready(function() {
         $('.box').css('backgroundColor','orange')
        })

       //4. ready简化写法
       $(function(){
         $('.box').css('backgroundColor','skyblue')
       })

       //5. onload 和 ready的执行先后
      $(window).on('load',function(){
        console.log('load');
      })
      $(function () {
        console.log('ready');
      })

2. 轮播图插件slick

jQuery的轮播图插件slick

  1. 下包:把插件下载到本地
  2. 导包:先导入jQuery,再导入插件,导入CSS(需要的话)
  3. 用包:根据文档(说明书)使用
(1) 导包

语法:

<!--引入插件所需要的样式表-->
<link rel="stylesheet" href="./slick/slick.css" />
<link rel="stylesheet" href="./slick/slick-theme.css" />
<!--先导入jQuery-->
 <script src="./jquery/jquery-3.5.1.js"></script>
<!--在jQuery之后引入插件-->
 <script src="./slick/slick.js"></script>
(2)用包

语法:

<div class ="your-class">
    <div>
        轮播图元素一
    </div>
    <div>
        轮播图元素二
    </div>
    <div>
        轮播图元素三
    </div>
</div>
$('.your-class').slick({
    autoplay:true,
    arrows:false,
    dots:true
})
常用配置含义默认值备注
autoplay轮播图效果自动执行falsetrue / false
arrows是否显示翻页按钮truetrue / false
prevArrow自定义上一页按钮标签选择器
nextArrow指定以下一页按钮标签选择器
dots是否显示指示器falsetrue / false

3.懒加载插件

jQuery的懒加载插件lazyload

  • 懒加载:图片用到了再去加载,常见于有大量图片的网页,比如电商
  1. 下包:把插件下载到本地
  2. 导包:先导入jQuery,再导入插件,导入CSS(需要的话)
  3. 用包:根据文档(说明书)使用
(1) 用包

语法:

<!--图片-->
<img class="lazyload" data-original="./images/1.png" alt=""/>
//找到希望懒加载的图片并调用lazyload方法
$('.lazyload').lazyload()
 <h3>04-懒加载插件</h3>
    <p>懒加载插件,用到了再去加载</p>
    <!-- 测试标签 -->
    <div class="wall"></div>
    <!-- 图片 -->
    <img class="lazyload" data-original="./images/1.png" alt="" />
    <img class="lazyload" data-original="./images/2.png" alt="" />
    <!-- 先导入jQuery -->
    <script src="./jquery/jquery-3.5.1.js"></script>
    <!-- 导入lazyload插件 -->
    <script src="./lazyload/jquery.lazyload.js"></script>
    <script>
      $('.lazyload').lazyload()
    </script>

4. 全屏滚动

jQuery的全屏滚动插件fullpage

  1. 下包:把插件下载到本地
  2. 导包:先导入jQuery,再导入插件,导入CSS(需要的话)
  3. 用包:根据文档(说明书)使用

语法:

<div id = "fullpage ">
    <div class = "section">
        第一屏
    </div>
    <div class = "section">
        第二屏
    </div>
    <div class = "section">
        第三屏
    </div>
</div>
$('#fullpage').fullpage({
    ...
})
常用配置含义默认值备注
navigation是否显示导航falsetrue / false
navigationPosition导航位置rightleft / right
anchors每个区域的锚链接名[ ]在地址栏
afterLoad区域加载完毕的回调函数,有2个参数参数:锚链接、索引
 // 整合全屏滚动效果
  $('#fullpage').fullpage({
    afterLoad(anchor, index) {
      console.log('afterLoad')
      console.log('anchor:', anchor)
      console.log('index:', index)
      $('.section').removeClass('current')
      setTimeout(function () {
        $('.section')
          .eq(index - 1)
          .addClass('current')
      }, 100)
    },
  })

5. 提交事件

form标签本身具有提交数据的能力,但是现在基本不这么用

测试结构:

<form>
    <input type = 'texe' placeholder = "用户名"/>
    <br/>
    <input type = "password" placeholder = '密码'>
    <br/>
    <input type = "submit" value = "提交"/>
    <button>
        提交
    </button>
</form>
  • 点击提交按钮,输入区域点击回车都会触发表单提交
  • 表单中的button默认就是提交按钮

现在比较流行在表单的submit事件中阻止默认行为,直接获取数据并提交

测试结构:

$('form').submit(function(e)) {
// 阻止默认行为
e.preventDefault()
//阻止默认行为
return false
 }

6. 日期选择器

jQuery的日期选择器插件datepicker,让用户在不同的浏览器下可以用一致的方式来选择日期

  1. 下包:把插件下载到本地
  2. 导包:先导入jQuery,再导入插件,导入CSS(需要的话)
  3. 用包:根据文档(说明书)使用

语法:

 <!-- 导入日期选择器的样式 -->
<link rel="stylesheet" href="./datepicker/datepicker.css" />
 <!-- 导入jQuery -->
 <script src="./jquery/jquery-3.5.1.js"></script>
 <!-- 导入日期选择器插件 -->
<script src="./datepicker/datepicker.js"></script>
<!-- 导入语言包 -->
<script src="./datepicker/i18n/datepicker.zh-CN.js"></script>
  • 默认显示的是英文,需要导入中文语言包
<!--准备html结构-->
<input type = "text" class = "datapicker"/>
    //调用插件方法
    $('.datapicker').datepicker({
    
})
常用配置含义默认值备注
autoPick是否自动选择当前日期falsetrue / false
autoHide选择日期之后是否自动关闭falsetrue / false
language语言模式需要结果语言包使用
  $('.datepicker').datepicker({
        language: 'zh-CN',
        autoPick: true,
        autoHide: true,
      })

7.表单验证

jQuery的表单验证插件validate,验证用户在表单中输入内容

  1. 下包:把插件下载到本地
  2. 导包:先导入jQuery,再导入插件,导入CSS(需要的话)
  3. 用包:根据文档(说明书)使用
(1)导包
<!-- 导入jQuery -->
    <script src="./jquery/jquery-3.5.1.js"></script>
    <!-- 导入 validate插件 -->
    <script src="./jquery-validate/jquery-validate.js"></script>
(2)用包
$('form').validate({
    // 配置
})
常用配置含义默认值备注
onBlur失去焦点时验证falsetrue / false
onSubmit提交表单时验证truetrue / fasle
sendForm是否提交表单truetrue / false
valid所有表单项验证通过执行的回调函数this是JQ对象
invalid至少一个表单项为通过验证时执行的回调函数this是JQ对象
description错误提示信息Object
自定义属性含义备注
data-required验证表单项不能为空不需要值
data-pattern基于正则表达式验证正则表达式
data-describedby指定显示错误信息的标签标签的id
data-description指定错误信息的内容和description中的属性对应
<input type = "password" name = "password" data-required data-pattern = ".{6,}"> 
  • 表单元素要放在form里面
 $('form').validate({
        sendForm: false,
        description: {
          password: {
            required: '密码不能为空!',
            pattern: '密码的长度必须大于等于6!'
          },
          nickname: {
            required: '昵称不能为空!'
          },
          agree: {
            required: '必须同意用户协议!'
          }
        },
        valid () {
          console.log('验证成功')
        },
        invalid () {
          console.log('验证失败')
        }
      })

8. 克隆

jQuery中封装了克隆(复制),节点的方法

语法:

// 不带事件
.clone()
// 带事件
.clone(true)
// 1. 为box中的按钮绑定事件: 把box的背景色变成黄绿色
     $('.box button').click(function() {
      $(this).parent().css('backgroundColor','yellowgreen')
     })
      // 2. 普通克隆
      $('.clone').click(function() {
        let $clone = $('.box').first().clone()
        $('body').append($clone)
      })
      // 3. 和事件一起克隆
      $('.deep-clone').click(function() {
        let $clone = $('.box').first().clone(true)
        $('body').append($clone)
      })
  • 方法返回的还是jQuery对象
  • 传入true事件也会一起克隆

9. 获取dom对象

jQuery封装了获取内部dom对象方法

测试代码:

// 播放视频
$('video').trigger('paly')
// 暂停视频
$('video').trigger('pause')
// 重置表单
$('form').trigger('reset')
  • jQuery通过trigger可以触发这些方法

语法:

// get方法获取
.get(索引)
// 中括号获取
[索引]
  • 索引从0开始
  • 获取到的是dom对象
  // 1.get方法
      let $btn = $('button')
      console.log('$btn:', $btn)
      let pauseBtn = $btn.get(1)
      console.log('pauseBtn:', pauseBtn)

      // 2. 中括号
      let playBtn = $btn[0]
      console.log('playBtn:', playBtn)

      // 3. 播放视频
      $('.play').click(function () {
        // $('video').play()
        // $('video').trigger('play')
        let video = $('video')[0]
        console.log('video:', video)
        video.play()
      })

      // 4. 暂停视频
      $('.pause').click(function () {
        // $('video').play()
        // $('video').trigger('pause')
        let video = $('video')[0]
        console.log('video:', video)
        video.pause()
      })

      // 5. 重置表单
      $('.reset').click(function () {
        // $('video').play()
        // $('form').trigger('reset')
        let form = $('form')[0]
        console.log('form:', form)
        form.reset()
      })

九、综合案例

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>13-人员管理</title>
    <link rel="stylesheet" href="./assets/datepicker/datepicker.css" />
    <!-- 自己的样式 -->
    <link rel="stylesheet" href="./css/index.css" />
  </head>

  <body>
    <h1>人员管理</h1>
    <div class="container">
      <!-- 新增按钮 -->
      <button class="btn add">新增</button>
      <!-- 表格 -->
      <table>
        <thead>
          <tr>
            <th width="150">姓名</th>
            <th width="150">手机</th>
            <th>生日</th>
            <th width="300">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr style="display: none;">
            <td class="td-name">小红</td>
            <td class="td-mobile">18888881111</td>
            <td class="td-birth">19900208</td>
            <td>
              <button class="btn edit">编辑</button>
              <button class="btn del">删除</button>
            </td>
          </tr>
          <tr>
            <td class="td-name">小红</td>
            <td class="td-mobile">18888881111</td>
            <td class="td-birth">19900208</td>
            <td>
              <button class="btn edit">编辑</button>
              <button class="btn del">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- 弹出框 -->
    <div class="dialog-wrap">
      <div class="form-container">
        <div class="title">
          <h3>新增</h3>
          <i class="close">×</i>
        </div>
        <form class="form">
          <label class="required">
            姓名:
            <input
              data-required
              data-describedby="nickname-error"
              data-description="nickname"
              type="text"
              class="nickname"
            />
            <span class="error" id="nickname-error"></span>
          </label>
          <label class="required">
            手机:
            <input
              data-required
              data-pattern="^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$"
              data-describedby="mobile-error"
              data-description="mobile"
              type="text"
              class="mobile"
            />
            <span class="error" id="mobile-error"></span>
          </label>
          <label class="required">
            生日:
            <input
              data-required
              data-describedby="birthday-error"
              data-description="birthday"
              type="text"
              class="birthday"
            />
            <span class="error" id="birthday-error"></span>
          </label>

          <div class="control">
            <a class="btn cancel">取消</a>
            <button class="btn">提交</button>
          </div>
        </form>
      </div>
    </div>
    <!-- 导入jQuery -->
    <script src="./jquery/jquery-3.5.1.js"></script>
    <!-- 导入日期选择器插件 -->
    <script src="./assets/datepicker/datepicker.js"></script>
    <!-- 导入日期选择器的语言包 -->
    <script src="./assets/datepicker/i18n/datepicker.zh-CN.js"></script>
    <!-- 导入表单校验插件 -->
    <script src="./assets/jquery-validate/jquery-validate.js"></script>
    <!-- 导入自己的js -->
    <!-- <script src="./js/index.js"></script> -->
    <script>
      // 初始化
      function clear() {
        $('.dialog-wrap').fadeOut(function () {
          $('.form')[0].reset()
          $('.form span').text('')
        })
      }
      let $editTr = undefined
      // 1.点击弹窗按钮
      $('.add').click(function (){
        $('.dialog-wrap h3').text('添加')
        $editTr = undefined
        $('.dialog-wrap').fadeIn()
      })
      // 2. 日期选择器
      $('.birthday').datepicker({
        language:'zh-CN',
        autoHide:true
      })
      //3. 表单验证
      $('form').validate({
        sendForm:false,
        description:{
          nickname:{
            required:'名称不能为空!'
          },
          birthday:{
            required: '生日不能为空!'
          },
          mobile:{
            required: '手机不能为空!',
            pattern:'手机格式错误'
          }
        },
        valid() {
         if($editTr === undefined) {
           let $tr = $('tbody tr').first().clone()
           let nickname = $('.nickname').val()
           let mobile = $('.mobile').val()
           let birthday = $('.birthday').val()
           $tr.find('.td-name').text(nickname)
           $tr.find('.td-mobile').text(mobile)
           $tr.find('.td-birth').text(birthday)
           $('tbody').append($tr)
           $tr.show()
           clear()
         } else {
           let nickname = $('.nickname').val()
           let mobile = $('.mobile').val()
           let birthday = $('.birthday').val()
           $editTr.find('.td-name').text(nickname)
           $editTr.find('.td-mobile').text(mobile)
           $editTr.find('.td-birth').text(birthday)
           clear()
         }
        }
      })
      // 4. 点击取消
      $('.cancel').click(function () {
        clear()
      })
      // 5. 点击关闭
      $('.close').click(function () {
        clear()
      })
      // 6. 删除
      $('tbody').on('click','.del',function () {
        let $tr = $(this).parent().parent()
        $tr.fadeOut(function (){
          $tr.remove()
        })
      })
      // 7. 进入编辑状态
      $('tbody').on('click','.edit',function (){
        let $tr = $(this).parent().parent()
        let name = $tr.find('.td-name').text()
        let mobile = $tr.find('.td-mobile').text()
        let birth = $tr.find('.td-birth').text()
        $('.dialog-wrap h3').text('编辑')
        $('.nickname').val(name)
        $('.mobile').val(mobile)
        $('.birthday').val(birth)
        $('.dialog-wrap').fadeIn()
        $editTr = $tr
      })
    </script>
  </body>
</html>

十、表单序列化 + 版本差异

1. 表单序列化

jQuery中封装了快速获取表单数据的方法,叫做序列化

语法:

$('form').serialize()
$('form').submit(function (e) {
        let data = $(this).serialize()
        console.log('data:',data);
        return false
      })
  1. 表单元素要有name属性才可以获取到value
  2. 获取到的数据格式是name1=value1&name2=value2字符串

2. 插件机制

插件是jQuery提供的扩展机制,本质是往jQuery原型对象上添加方法

语法:

jQuery.fn.extend({
    插件名(参数){
        // 逻辑
    }
})
  1. jQuery$的别名
  2. jQuery内部也是通过这种方法添加方法
// 1.基本使用
      $.fn.extend({
        sayHello () {
          console.log('吃了没!')
          console.log(this)
        }
      })
      let $box = $('.box')
      console.log('$box:', $box)
      $box.sayHello()
      // 2.修改背景色插件
     $.fn.extend({
      setBgColor(color) {
        this.css('backgroundColor',color)
      }
     })
     $('.box').setBgColor('skyblue')
     $('p').setBgColor('pink')
     $('h3').setBgColor('red')

3.工具方法

jQuery除了封装了大量的DOM操作外,还提供了一些工具方法,这些方法通过$或者jQuery直接调用

语法:

// 遍历方法
$.each(数组,function(下标,值){
    
})
//遍历并返回新数组
$.map(数组,function(){
    // 返回新的值
})
  • 不仅仅只有这个2个方法
  • 逐步被ES6及更高级的版本新增特性取代

4. 版本差异

jQuery主要有3个大的版本

  1. x:兼容低版本的ie,最后一个版本是1.12.3
  2. x:不兼容低版本ie,不在更新
  3. x:不兼容低版本ie,更新中
    // 6. 删除
    $(‘tbody’).on(‘click’,‘.del’,function () {
    let $tr = $(this).parent().parent()
    $tr.fadeOut(function (){
    $tr.remove()
    })
    })
    // 7. 进入编辑状态
    $(‘tbody’).on(‘click’,‘.edit’,function (){
    let $tr = $(this).parent().parent()
    let name = $tr.find(‘.td-name’).text()
    let mobile = $tr.find(‘.td-mobile’).text()
    let birth = $tr.find(‘.td-birth’).text()
    $(‘.dialog-wrap h3’).text(‘编辑’)
    $(‘.nickname’).val(name)
    $(‘.mobile’).val(mobile)
    $(‘.birthday’).val(birth)
    $(‘.dialog-wrap’).fadeIn()
    $editTr = $tr
    })

## 十、表单序列化 + 版本差异

### 1. 表单序列化

**jQuery中封装了快速获取表单数据的方法,叫做序列化**

**语法:**

~~~js
$('form').serialize()
$('form').submit(function (e) {
        let data = $(this).serialize()
        console.log('data:',data);
        return false
      })
  1. 表单元素要有name属性才可以获取到value
  2. 获取到的数据格式是name1=value1&name2=value2字符串

2. 插件机制

插件是jQuery提供的扩展机制,本质是往jQuery原型对象上添加方法

语法:

jQuery.fn.extend({
    插件名(参数){
        // 逻辑
    }
})
  1. jQuery$的别名
  2. jQuery内部也是通过这种方法添加方法
// 1.基本使用
      $.fn.extend({
        sayHello () {
          console.log('吃了没!')
          console.log(this)
        }
      })
      let $box = $('.box')
      console.log('$box:', $box)
      $box.sayHello()
      // 2.修改背景色插件
     $.fn.extend({
      setBgColor(color) {
        this.css('backgroundColor',color)
      }
     })
     $('.box').setBgColor('skyblue')
     $('p').setBgColor('pink')
     $('h3').setBgColor('red')

3.工具方法

jQuery除了封装了大量的DOM操作外,还提供了一些工具方法,这些方法通过$或者jQuery直接调用

语法:

// 遍历方法
$.each(数组,function(下标,值){
    
})
//遍历并返回新数组
$.map(数组,function(){
    // 返回新的值
})
  • 不仅仅只有这个2个方法
  • 逐步被ES6及更高级的版本新增特性取代

4. 版本差异

jQuery主要有3个大的版本

  1. x:兼容低版本的ie,最后一个版本是1.12.3
  2. x:不兼容低版本ie,不在更新
  3. x:不兼容低版本ie,更新中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值