jQuery从入门到精通

本文详细介绍了jQuery的使用,从基础概念到核心函数、对象的使用,再到事件处理、动画效果和插件的运用。通过实例演示,帮助读者掌握jQuery的各个方面,实现快速、高效地进行网页开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1. 初识jQuery

1.1  What?

1.2 Why?

1.3 How? 

2. jQuery的2把利器

2.1 jQuery核心函数

2.2. jQuery核心对象(通过.调用内部的方法)

3. 使用jQuery核心函数

3.1. 选择器:

3.2 层次选择器

3.3 过滤选择器

3.4 表单小练习

3.5 表单选择器

3.6 jQuery的$工具方法

3.7 多Tab点击切换

3.8 jQuery属性

4. 使用jQuery对象

5. jQuery插件

6. 练习

 


 

1. 初识jQuery

  1. 封装简化DOM(CRUD)/Ajax:增删改查(create、read、update、delete)。
  2. Write less,do more。 

1.1  What?

https://jquery.com/

一个优秀的JS函数库。

使用了jQuery的网站超90%。

中大型WEB项目开发首选。

1.2 Why?

HTML元素选取(选择器);HTML元素操作;CSS操作;HTML事件处理;

隐式遍历(迭代):一次操作多个元素;JS动画效果;链式调用;读写合一

浏览器兼容;易扩展插件;ajax封装……

1.3 How? 

  1. 区别jQuery的不同版本

      答:(1)1.x:兼容老版本IE;文件更大;(使用率更高

             (2)2.x:部分IE8及以下不支持;文件小,执行效率更高;

             (3)3.x:提供了一些新的API;提供不包含ajax/动画API的版本。

      2. 区别2种js库库文件:

      答:开发版(测试版);生产版(压缩版)。

             压缩版不止去除了空格、换行,除此之外,变量名变成了a、b、c等,可读性较低。

     3.  jQuery使用:

      答:(1)使用jQuery核心函数:$/jQuery;

              (2)使用jQuery核心对象:执行$()返回的对象。

                二者区别:见jQuery的两把利器。

     4. 引入jQuery方法:

      答:(1)服务器本地库;

             (2)CDN远程库。(得有网哦O(∩_∩)O哈哈~

                       项目上线时,一般使用比较靠谱的CDN资源库;减轻服务器负担。

                       常见的CDN资源库(综合):https://www.jq22.com/jquery/jquery.html 

                                                                      https://www.bootcdn.cn/   (BootCDN) 

                            

                                      

                      

 

 

2. jQuery的2把利器

  1. 执行jQuery函数返回的的就是jQuery对象。
  2. jQuery唯一暴露的就是jQuery和$,其余的都看不见。
 // 1. jQuery函数:直接可用
    console.log($,typeof $)//函数类型
    console.log($ instanceof Object)//函数也是对象
    console.log(jQuery===$)//true jQuery唯一暴露的就是jQuery和$,其余的都看不见
    // 2. jQuery对象:执行jQuery得到它
    console.log($() instanceof Object)// true

 

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>初识jQuery</title>
    <!-- 使用原生DOM -->
    <script>
        window.onload = function () {
            var btn01 = document.getElementById('btn01');
            var username = document.getElementById('username');
            btn01.onclick = function () {
                // 获取输入的文本值
                var v = username.value;
                alert(v);
            }
        }
    </script>
    <!-- 使用jQuery实现 -->
    <script src="https://www.jq22.com/jquery/jquery-1.10.2.js"></script>
    <script>
        //绑定文档加载完成的监听
        jQuery(function(){
            $('#btn02').click(function(){//给btn02绑定点击监听
                var username=$('#username').val()//jQuery定义的函数通过val()代表读取内容
                alert(username)
            })
        })
    </script>
</head>
 
<body>
    <!-- 需求:点击“确定”按钮,提示输入的值 -->
    用户名:<input type="text" id="username">
    <button id="btn01">确定(原声版)</button>
    <button id="btn02">确定(jQuery版)</button>
 
</body>
 
 
</html>

2.1 jQuery核心函数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery函数的使用</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        


        // ①参数为函数:当DOM加载完成后,执行此回调函数
        $(function () { //绑定文档加载完成的监听

        // 需求1. 点击按钮,显示按钮的文本,显示一个新的输入框

            //②参数为选择器字符串:查找所有匹配的标签,并将它们封装成jQuery对象
            $('#btn').click(function(){//绑定点击事件监听
               
                alert(this.innerHTML) //this是发生事件的dom元素,与是否使用jQuery无关(<button>)

                //③参数为DOM对象:将dom对象封装成jQuery对象
                // alert($(this).html())//传参数就是写,不传参数就是读

                //④参数为html标签字符串:创建标签对象并将其封装成jQuery对象
                $('<input type="text" name="msg3"><br>').appendTo('div')
            })

        // 需求2. 遍历输出数组中所有元素值
        var arr=[2,4,7,9]
        //$.each():隐式遍历数组
        $.each(arr,function(index,item){
            console.log(index,item)// 0 2; 1 4; 2 7; 3 9
        })

        //需求3. 去掉”  my atguigu  “两端的空格
        var str="  my atguigu  "
        console.log('----'+str.trim()+'----')//---my atguigu----
        console.log('---'+$.trim(str)+'----')//---my atguigu----
        })
    </script>
</head>

<body>
    <div>
        <button id="btn">测试</button>
        <br>
        <input type="text" name="msg1"><br>
        <input type="text" name="msg2"><br>

    </div>
</body>

</html>

2.2. jQuery核心对象(通过.调用内部的方法

  1. 即执行jQuery核心函数返回的对象;
  2. jQuery对象内部包含的是dom元素对象的伪数组(可能只有一个元素);
  3. jQuery对象拥有很多有用的属性和方法,让程序员能方便的操作dom。

 2.2.1 基本行为:

  1. size()/length:返回jQuery 对象中元素的个数。
  2. [index]/get(index):根据下标得到对应的dom元素。
  3. each():遍历内部的dom元素。
  4. index()。

2.2.2 属性:操作内部标签的属性或值。

2.2.3 CSS:操作标签的样式。

2.2.4 文档:对标签进行增删改查操作。

2.2.5 筛选:根据指定的规则过滤内部的标签。

2.2.6 事件:处理事件监听相关。

2.2.7 效果:实现一些动画效果。

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function(){
        //需求1. 统计一共有多少个按钮
          var $buttons=$('button')
          console.log($buttons.length,$buttons.size())//4 4 

        //需求2. 取出第二个button的文本
        console.log($buttons[1].innerHTML,$buttons.get(1).innerHTML)//测试二 测试二

        //需求3. 输出所有button标签的文本
        $buttons.each(function(index,domEle){
            console.log(index,domEle.innerHTML)//0 “测试一” 1 “测试二” 2 “测试三” 3 “测试四”
            console.log(this)//此处this就相当于domELe  <button>测试一</button> <button>测试二</button> <button>测试三</button> <button>测试四</button> 
            console.log(this.innerHTML)// “测试一”  “测试二”  “测试三”  “测试四”
        })

        //需求4. 输出“测试三”按钮是所有按钮中的第几个
        console.log($('#btn03').index())//2

        })

    </script>
    <button>测试一</button>
    <button>测试二</button>
    <button id="btn03">测试三</button>
    <button>测试四</button>
</head>

<body>

</body>

</html>

 1. 伪数组

(1)Object对象

(2)Length属性

(3)数值下标属性

(4)没有数组特别的方法:forEach()、push()、pop()、splice()。

3. 使用jQuery核心函数

3.1. 选择器:

  (1)说明:选择器本身只是一个有特定语法规则的字符串,没有实质用处。它的基本语法规则使用的就 是CSS的选择器语法,并对基进行了扩展。只有调用$(),并将选择器作为参数传入才能起作用。$(selector)作用:根据选择器规则在整个文档中查找所有匹配的标签的数组,并封装成jQuery对象返回。

  (2)分类:

          ①基本选择器:

              

          ②层次选择器:后代;孩子;后面的兄弟;

              

          ③过滤选择器:在原有选择器匹配的元素中进一步进行过滤的选择器。

              分类:基本过滤选择器 内容过滤选择器 ;可见性过滤选择器 ;属性过滤选择器 。

              :eq(index):找出某一个;

          ④表单选择器:表单;表单对象属性。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () { //绑定文档加载完成的监听
            //需求1. 选择id为div1的元素
            $('#div1').css('background', 'red')
            //需求2. 选择所有的div元素
            $('div').css('background','red')
            //需求3. 选择所有class属性为box的元素
            $('.box').css('background','blue')
            //需求4. 选择所有div和span元素
            $('div,span').css('background','yellow')
            //需求5. 选择所有class属性为box的div元素
            $('div.box').css('background','green')
        })
    </script>
</head>

<body>
    <div id="div1" class="box">div1(class="box")</div>
    <div id="div2" class="box">div1(class="box")</div>
    <div id="div3">div3</div>
    <span class="box">span(class="box")</span>
    <br>
    <ul>
        <li>AAAAA</li>
        <li title="hello">BBBBB(title="hello")</li>
        <li class="box">CCCCC(class="box")</li>
        <li title="hello">DDDDD(title="hello")</li>
    </ul>
</body>

</html>

3.2 层次选择器

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () { //页面加载完成的监听
            // 需求1. 选中ul下所有的span
            $('ul span').css('background', 'red')
            // 需求2. 选中ul下所有的子元素span
            $('ul>span').css('background', 'yellow')
            // 需求3. 选中class为box下的一个li
            $('.box +li').css('background', 'orange')
            // 需求4. 选中ul下(后代)的class为box的元素后面的所有兄弟元素
            $('ul .box ~*').css('background', 'green')


        })
    </script>
</head>

<body>
    <ul>
        <li>AAAAA</li>
        <li class="box"><span>BBBBB</span></li>
        <li title="hello"><span>DDDD</span></li>
        <span>EEEE</span>

    </ul>
</body>

</html>

3.3 过滤选择器

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () { //页面加载完成监听
            // 1.选择第一个div
            $('div:first').css('background', 'red')
            // 2.选择最后一个class为box的元素
            $('.box:last').css('background', 'yellow')
            // 3.选择所有class属性不为box的div
            $('div:not(.box)').css('background', 'green') //没有class属性的也可以
            // 4. 选择第二个和第三个li元素
            // $('li:gt(0):lt(2)').css('background', 'blue')//多个选择器是依次执行的
            $('li:lt(3):gt(0)').css('background', 'blue')
            // 5.选择内容为BBBBB的li
            $('li:contains(BBBBB)').css('background', 'purple')
            // 6.选择隐藏的li
            console.log($('li:hidden').length,$('li:hidden')[0])
            // 7.选择所有title属性的li元素
            $('li[title]').css('background', 'red')
            // 8.选择所有属性title为hello的li元素
            $('li[title=hello]').css('background', 'purple')

        })
    </script>
</head>

<body>
    
    <div id="div1" class="box">class为box的div1</div>
    <div id="div2" class="box">class为box的div2</div>
    <div id="div3">div3</div>
    <span class="box">class为box的span</span>
    <br>
    <ul>
        <li>AAAAA</li>
        <li title="hello">BBBBB</li>
        <li class="box">CCCCC</li>
        <li title="hello">DDDDD</li>
        <li title="two">BBBBB</li>
        <li style="display: none;">我本来是隐藏的</li>
       
    </ul>

</body>

</html>

3.4 表单小练习

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {
            $('#data>tbody>tr:odd').css('background', 'rgb(203,207,255)')
        })
    </script>
    <style>
        table {

            width: 50%;
            height: 20%;

        }

        td {
            padding: 8px;
        }

        .heading {
            text-align: center;
            background-color: rgb(50, 57, 158);
        }
    </style>
</head>

<body>
    <table border="1px solid black" cellspacing="0" id="data">
        <thead>
            <tr class="heading">
                <td>姓名</td>
                <td>工资</td>
                <td>入职时间</td>
                <td>操作
                </td>
            </tr>
        </thead>
        <tbody>
           
            <tr>
                <td>Tom</td>
                <td>$3500</td>
                <td>2010-12-1</td>
                <td><a href="#">删除</a>
                </td>
            </tr>
            <tr>
                <td>Mary</td>
                <td>$3400</td>
                <td>2010-10-25</td>
                <td><a href="#">删除</a>
                </td>
            </tr>
            <tr>
                <td>King</td>
                <td>$3900</td>
                <td>2009-08-17</td>
                <td><a href="#">删除</a>
                </td>
            </tr>
            <tr>
                <td>Scott</td>
                <td>$3800</td>
                <td>2012-11-17</td>
                <td><a href="#">删除</a>
                </td>
            </tr>
            <tr>
                <td>Smith</td>
                <td>$3100</td>
                <td>2014-01-27</td>
                <td><a href="#">删除</a>
                </td>
            </tr>
            <tr>
                <td>Allen</td>
                <td>$3700</td>
                <td>2011-12-05</td>
                <td><a href="#">删除</a>
                </td>
            </tr>
        </tbody>

    </table>
</body>

</html>

3.5 表单选择器

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () { //添加加载完成监听
            //1. 选择不可用的文本输入框
            $(':input:disabled').css('background', 'red')
            //2. 显示选择爱好的个数
            console.log($(':checkbox:checked').length)//3
            //3. 显示选择的城市名称(在提交按钮后)
            $(':submit').click(function(){
               var name= $('select>option:selected').html()//选择option的标签文本
            //    name=$('select').val()//选择option的value属性
               alert(name)
            })

        })
    </script>
</head>

<body>
    <form>
        用户名:<input type="text"><br>
        密码:<input type="text"><br>
        爱好:
        <input type="checkbox" name="hobby" value="basketball" checked=true>篮球
        <input type="checkbox" name="hobby" value="football" checked=true>足球
        <input type="checkbox" name="hobby" value="badminton" checked=true>羽毛球<br>
        性别:
        <input type="radio" name="gender">男
        <input type="radio" name="gender">女<br>
        邮箱:<input type="text" disabled=true><br>
        所在地:
        <select name="address">
            <option value="beijing">北京</option>
            <option value="tianjin" selected="selected"> 天津</option>
            <option value="hebei">河北</option>
        </select><br>
        <input type="submit" value="提交">
    </form>


</body>

</html>

3.6 jQuery的$工具方法

    

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        /* 
            1. $.each():遍历数组或对象中的数据
            2. $.trim():去除字符串两边的空格
            3. $.type(obj):得到数据的类型
            4. $.isArray(obj):判断是否是数组
            5. $.isFunction(obj):判断是否是函数
            6. $.parseJSON(json):解析json字符串转换js对象/数组
        */
       $(function(){//添加页面加载完成监听
        //1. $.each():遍历数组或对象中的数据
        var obj={
            name:'Tom',
            setName:function(name){
                this.name=name
            }
        }
        $.each(obj,function(key,value){
            console.log(key,value)
        })
         //3. $.type(obj):得到数据的类型
        console.log($.type($))//function
        //4. $.isArray(obj):判断是否是数组
        console.log($.isArray($('body')),$.isArray([]))//伪数组并非真的数组 flase true
        //5. $.isFunction(obj):判断是否是函数
        console.log($.isFunction($))//true
       //6. $.parseJSON(json):解析json字符串转换js对象/数组
       var json='{"name":"Tom","age":12}'// js对象:{}
       //json对象==>JS对象
       console.log($.parseJSON(json))
       json='[{"name":"Tom","age":12},{"name":"Jack","age":12}]'//json数组
       console.log(json)
       console.log($.parseJSON(json))
        /* 
            JSON.parse(jsonString)//json字符串--->js对象/数组
            JSON.stringify(jsObj/jsArr)//js对象/数组--->json字符串
        */
       })
    </script>
</head>
<body>
    
</body>
</html>

3.7 多Tab点击切换

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        li {
            list-style: none;
            display: inline;
            padding: 10px;
            float: left;
        }

        .class1,
        .content1 {
            background-color: rgb(231, 163, 163);
        }

        .class2,
        .content2 {
            background-color: rgb(226, 198, 147);
        }

        .class3,
        .content3 {
            background-color: rgb(178, 178, 241);
        }

        div:not(#container) {
            clear: left;
            width: 400px;
            height: 200px;
            padding: 10px;
        }

         
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function(){//页面加载完成监听
            var currentIndex=0

            var $contents=$('#container>div')
            // 给三个a添加监听
            $('#tab>li').click(function(){//隐式遍历
                //方式一
                // $('.class1').click(function(){
                //     $('.content2,.content3').css('display','none')
                //     $('.content1').css('display','block')

                // })
                // $('.class2').click(function(){
                //     $('.content1,.content3').css('display','none')
                //     $('.content2').css('display','block')

                // })
                // $('.class3').click(function(){
                //     $('.content2,.content1').css('display','none')
                //     $('.content3').css('display','block')

                // })
                

                //方式二
                // $contents.css('display','none')
                // var index=$(this).index()
                // $contents[index].style.display='block'

                //方式三(其实只需隐藏当前显示的div)
                $contents[currentIndex].style.display='none'
                var index=$(this).index()
                $contents[index].style.display='block'
                //更新下标
                currentIndex=index

            })

        })
    </script>
</head>

<body>
    <h2>多Tab点击切换</h2>
    <ul id="tab">
        <li class="class1">10元套餐</li>
        <li class="class2">30元套餐</li>
        <li class="class3">50元包月</li>
    </ul>

    <div id="container">
        <div class="content1">
            10元套餐详情:
            每月套餐内拨打100分钟,超出部分2毛/分钟
        </div>
        <div class="content2" style="display: none;">
            30元套餐详情:
            每月套餐内拨打300分钟,超出部分1.5毛/分钟
        </div>
        <div class="content3" style="display: none;">
            50元套餐详情:
            每月无限量随心打
        </div>
    </div>
</body>

</html>

3.8 jQuery属性

 

  1. 操作标签的属性、标签体文本。
  2. attr(name)/attr(name,value):读写布尔值的标签属性。
  3. prop(name)/prop(name,value):读写非布尔值的标签属性。
  4. removeAttr(name)/removeProp(name):删除属性。
  5. addClass(classValue):添加class。
  6. removeClass(classValue):移除指定class。
  7. val()/val(value):读写标签的value。
  8. html()/html(htmlString):读取标签体文本。

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () { //添加事件加载监听
            //1. 读取第一个div的title属性
            // console.log($('div:first').attr('title'))

            //2. 给所有的div设置name属性(value为atguigu)
            // $('div').attr('name','atguigu')

            //3. 移除所有div的title属性
            // $('div').removeAttr('title')

            //4. 给所有的div设置class='atguigu'
            // $('div').attr('class','guiguClass')

            //5. 给所有的div添加class='abc'
            // $('div').addClass('abc')

            //6. 移除所有div的guiguClass的class
            // $('div').removeClass('guiguClass')

            //7. 得到最后一个li的标签体文本
            // console.log($('li:last').html()) //不用text()因为兼容性不太高 span>BBBBB</span>
            // console.log($('li:last').text()) //BBBBB
            
            //8. 设置第一个li的标签体为“<h1>mmmmmmmmmmm</h1>”
            // $('li:first').html('<h1>mmmmmmmmmmm</h1>')

            //9. 得到输入框中的value值
            // console.log($(':text').val())//guiguClass

            //10. 将输入框中的值设置为atguigu
            // $(':text').val('atguigu')

            //11. 点击“全选”按钮实现全选
            //attr():操作属性值为非布尔值的属性
            //prop():专门操作属性值为布尔值的属性
            $('button:first').click(function(){
                $(':checkbox').prop('checked',true)
            })
            //12. 点击“全不选”按钮实现全不选
            $('button:last').click(function(){
                $(':checkbox').prop('checked',false)
            })

        })
    </script>
</head>

<body>
    <div id="div1" class="box" title="one">class为box的div1</div>
    <div id="div2" class="box" title="two">class为box的div2</div>
    <div id="div3">div3</div>
    <span class="box">class为box的span</span>
    <br>
    <ul>
        <li>AAAAA</li>
        <li class="box2" title="hello">BBBBB</li>
        <li class="box">CCCCC</li>
        <li title="hello">DDDDD</li>
        <li title="two"><span>BBBBB</span></li>
    </ul>
    <input type="text" name="username" value="guiguClass">
    <br>
    <input type="checkbox" >
    <input type="checkbox">
    <br>
    <button>选中</button>
    <button >不选中</button>
</body>

</html>

4. 使用jQuery对象

4.1 CSS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function(){//添加页面加载完成的监听
            // 1.得到第一个p标签的颜色
        //    console.log( $('p:first').css('color'))//rgb(0,0,255)
            // 2.设置所有p标签的文本颜色为red
            // $('p').css('color','red')
            // 3.设置第2个p的字体颜色(#ff0011),背景(blue),宽(300px),高(30px)
            $('p:eq(1)').css({
                color:'#ff0011',
                background:'blue',
                width:'300px',
                height:'30px'
            })
        })
    </script>
</head>
<body>
    <p style="color: blue;">妲己,会一直爱主人</p>
    <p style="color: green;">旋转跳跃</p>
</body>
</html>

 4.2 offset和position

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #div1 {
            background-color: blue;
            width: 300px;
            height: 300px;
            position: absolute;
            top: 20px;
            left: 20px;


        }

        #div2 {
            position: absolute;
            top: 50px;
            width: 100px;
            height: 100px;
            background-color: red;

        }

        #div3 {
            position: absolute;
            top: 350px;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () { //添加页面加载完成监听
            /* 
                offset():相对于页面左上角的坐标
                position():相对于父元素左上角的坐标
            */
            $('#btn01').click(function () {
                var offset = $('#div1').offset()
                //1. 打印div1相对于页面左上角的位置
                console.log(offset.left, offset.top)
                offset = $('#div2').offset()
                //2. 打印div2相对于页面左上角的位置
                console.log(offset.left, offset.top)
                //3. 打印div1相对于父元素左上角的位置
                var position=$('#div1').position()
                console.log(position.left,position.top)
                //4. 打印div2相对于父元素左上角的位置
                position=$('#div2').position()
                console.log(position.left,position.top)
            })
            $('#btn02').click(function () {
                $('#div2').offset({
                    top:30,
                    left:70
                })
            })



        })
    </script>
</head>

<body>
    <div id="div1">
        <div id="div2">测试offset</div>
    </div>
    <div id="div3">
        <button id="btn01">读取offset和position</button>
        <button id="btn02">设置offset</button>
    </div>
</body>

</html>

4.3 scroll

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        /* 
            1. scrollTop():读取/设置滚动条的Y坐标
            2. $(document.body).scrollTop()+$(document.documentElement).scrollTop()
                读取页面滚动条的Y坐标(兼容chrome和IE)
            3. $('body,html').srcollTop(60);
                滚动到指定位置(兼容chrome和IE)
        */

        $(function () {
            //需求1.得到div或页面滚动体的坐标
            $('#btn01').click(function () {
                console.log($('div').scrollTop())
                // console.log($('body').scrollTop())//这样写chrome不支持
                // console.log($('html').scrollTop())//这样写IE不支持
                console.log($('body').scrollTop() + $('html').scrollTop())

            })
            // 需求2.让div或页面的滚动条滚动到指定位置
            $('#btn02').click(function () {
                $('body,html').scrollTop(60)
            })
        })
    </script>
</head>

<body>
    <div style="border: 1px solid black;width: 100px;height: 150px;overflow: auto;">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sapiente quae ipsam libero ipsum at quasi beatae est
        esse iure earum odit atque aspernatur, nemo, consequuntur nihil, eaque sit ratione tenetur?
    </div>
    <br>
    <br>
    <br>
    <button id="btn01">得到scrollTop</button>
    <button id="btn02">设置scrollTop</button>

</body>

</html>

4.4 常见效果

4.5 元素尺寸


        1. 内容尺寸 height():height  width():width
        2. 内部尺寸 innerHeight():height+padding innerWidth():width+padding
        3. 外部尺寸 outerHeight(flase/true):height+padding+border 如果是true加上margin
                outerWidth(flase/true):height+padding+border 如果是true加上margin
     

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 100px;
            height: 150px;
            background-color: red;
            padding: 10px;
            border: 10px solid #fbd850;
            margin: 10px;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
   
    <script>
        $(function(){
            var $div=$('div')
            //1.内容尺寸
            console.log($div.width(),$div.height())
            //2. 内部尺寸 
            console.log($div.innerWidth(),$div.innerHeight())// 120 170
            //3. 外部尺寸 
            console.log($div.outerWidth(),$div.outerHeight())//140 190
            console.log($div.outerWidth(true),$div.outerHeight(true))// 160 210
        })
    </script>
</head>
<body>
    <div></div>
</body>
</html>

4.6 jQuery对象的过滤

在jQuery对象内部的元素中找出部分匹配的元素,并封装成新的jQuery对象返回。

  • first()
  • last()
  • eq(index)
  • filter(selctor):对当前元素提要求
  • not(selctor):对当前元素提要求并取反
  • has(selctor):对子孙元素提要求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        // 原本过滤器过滤出来的东西即使用get方法或[index],得到的都是dom对象,而这种筛选方法得到的是jQuery对象
        $(function(){//添加页面加载完成监听
            var $lis=$('ul>li')
            //1. ul下li标签第一个
            // $lis.first().css('background','red')
            //2. ul下li标签最后一个
            // $lis.last().css('background','red')
            //3. ul下li标签第二个
            // $lis.eq(1).css('background','red')
            //4. ul下li标签中title属性为hello的
            // $lis.filter('[title=hello]').css('background','red')
            //5. ul下li标签中title属性不为hello的
            // $lis.filter('[title][title!=hello]').css('background','red')
            //6. ul下标签中有span子标签的
            $lis.has('span').css('background','orange')


        })
    </script>
</head>
<body>
    <ul>
        <li>AAAAA</li>
        <li class="box1" title="hello">BBBBB</li>
        <li class="box">CCCCC</li>
        <li title="hello">DDDDD</li>
        <li title="two"><span>BBBBB</span></li>
    </ul>
    <li>eeeee</li>
    <li>EEEEE</li>
    <br>
</body>
</html>

4.7 jQuery对象的查找

在已经匹配出的元素集合中根据选择器查找孩子/父母/兄弟标签,并封装成新的jQuery对象返回

  1. children() :子标签中找。
  2. find():后代标签中找。
  3. parent():父标签。
  4. prevAll():前面所有的兄弟标签。
  5. nextAll():后面所有的兄弟标签。
  6. sibling():所有兄弟。
  7. parent():父元素。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function(){//添加页面加载完成监听
        var $ul=$('ul')
        var $li=$('#cc')
            //1. ul标签的第2个span子标签
            // $ul.children('span:eq(1)').css('background','red')
            //2. ul标签的第2个span后代标签
            // $ul.find('span:eq(1)').css('background','orange')
            //3. ul标签的父标签
            // $ul.parent().css('background','yellow')
            //4. id为cc的li标签的前面所有的li标签
            // $li.prevAll('li').css('background','green')
            //5. id为cc的li标签的所有兄弟li标签
            $li.siblings('li').css('background','blue')


        })
    </script>
</head>

<body>
    <div id="div1" class="box" title="one">class为box的div1</div>
    <div id="div2" class="box">class为box的div2</div>
    <div id="div3">div3</div>
    <span class="box">class为box的span</span>
    <br>
    <div>
        <ul>
            <span>span文本1</span>
            <li>AAAAA</li>
            <li class="box2" title="hello">BBBBB</li>
            <li class="box" id="cc">CCCCC</li>
            <li title="hello">DDDDD</li>
            <li title="two"><span>span文本2</span></li>
            <span>span文本3</span>
    
        </ul>
        <span>span文本4</span>
        <li>eeeee</li>
        <li>EEEEE</li>
        <br>
    </div>
</body>

</html>

 4.8 爱好选择器

button与submit的区别:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function(){//添加页面加载完成监听
        

            var $checkedAllBox=$('#checkedAllBox')
            var $items=$(':checkbox[name=items]')
            //1. 点击”全选“:选中所有爱好
            $('#checkedAllBtn').click(function(){
                $items.prop('checked',true)
                $checkedAllBox.prop('checked',true)

            })
            // 2. 点击“全不选”;所有爱好都不勾选
            $('#checkedNoBtn').click(function(){
                $items.prop('checked',false)
                $checkedAllBox.prop('checked',false)

            })
            // 3. 点击“反选”:改变所有爱好的勾选状态
            $('#checkedRevBtn').click(function(){
                // $items.prop('checked',true)?false:true这样写有问题
                $items.each(function(){
                    this.checked=!this.checked
                })
                $checkedAllBox.prop('checked',$items.filter(':not(:checked)').length===0)//没有被勾对号的就是全选即为true

            })
            //4. 点击“提交”:提示所有勾选的爱好
            $('#sendBtn').click(function(){
               $items.filter(':checked').each(function(){
                   alert(this.value)
               })
            })
            //5. 点击“全选/全不选”:选中所有爱好,或者全不选中
            $checkedAllBox.click(function(){
                $items.prop('checked',this.checked)
            })
            //6. 点击某个爱好时,必要时更新“全选/全不选”的选中状态
            $items.click(function(){
                $checkedAllBox.prop('checked',$items.filter(':not(:checked)').length===0)
            })
        })
    </script>
</head>
<body>
    你爱好的运动是?
    <input type="checkbox" name="select" id="checkedAllBox" >全选/全不选
    <br>
    <input type="checkbox" value="football" name="items">足球
    <input type="checkbox" value="basketball" name="items" >篮球
    <input type="checkbox" value="badminton" name="items">羽毛球
    <input type="checkbox" value="table-tennis" name="items">乒乓球
    <br>
    <input type="submit" value="全选" id="checkedAllBtn">
    <input type="submit" value="全不选" id="checkedNoBtn">
    <input type="submit" value="反选" id="checkedRevBtn">
    <input type="submit" value="提交" id="sendBtn">

</body>
</html>

 4.9 文档处理模块(CUD)

  1. 增加
    1. append()/appendTo():插入后部。
    2. prepend()/prependTo():插入前部。
    3. before():插到前面。
    4. after():插到后面。
  2. 删除
    1. remove():将自己及内部的孩子都删除。
    2. empty():掏空(自己还在)
  3. 更新
    1. replaceWith()

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {
            var $ul1= $('#ul1')
            var $ul2= $('#ul2')
            //1.向id为ul1的ul下添加一个span(最后)
            // $ul1.append('<span>123</span>')
            // $('<span>appendTo()添加的span</span>').appendTo($ul1)

            //2.向id为ul1的ul下添加一个span(最前)
            // $ul1.prepend('<span>123</span>')
            // $('<span>prependTo()添加的span</span>').prependTo($ul1)
 
            //3.在id为ul1的ul下的li(title为hello)的前面添加span
            // $ul1.children('li[title=hello]').before('<span>123</span>')

            //4.在id为ul1的ul下的li(title为hello)的后面添加span
            // $ul1.children('li[title=hello]').after('<span>123</span>')

            //5.将在id为ul2的ul下的li(title为hello)全部替换为p
            // $ul2.children('li[title=hello]').replaceWith('<p>123</p>')
            // $('<p>123</p>').replaceAll($ul2.children('li[title=hello]'))


            //6. 移除id为ul2的ul下的所有li
            // $ul2.children('li').remove()//没有li
            // $ul2.children('li').empty()//清空内容
        })
    </script>
</head>

<body>
    <ul id="ul1">
        <li>AAAAA</li>
        <li title="hello">BBBBB</li>
        <li class="box">CCCCC</li>
        <li title="hello">DDDDD</li>
        <li title="two">EEEEE</li>
        <li>FFFFF</li>

    </ul>
    <br>
    <ul id="ul2">
        <li>aaa</li>
        <li title="hello">bbb</li>
        <li class="box">ccc</li>
        <li title="hello">ddd</li>
        <li title="hello">eee</li>

    </ul>
</body>

</html>

4.10 练习增删改查

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table,
        div {
            margin: 30px auto;
        }

        table {
            text-align: center;
        }

        thead tr {
            font-weight: bolder;
        }

        div {
            border: 1px solid black;
            width: 300px;
            height: 200px;
            padding-left: 10px;
        }

        #submit {
            display: block;
            margin: 10px auto;
        }

        #name,
        #email,
        #salary {
            width: 230px;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {


            //1.添加
            $('#submit').click(function () {
                //1.1 收集输入的数据
                var $name = $('#name')
                var $email = $('#email')
                var $salary = $('#salary')
                var name = $('#name').val()
                var email = $('#email').val()
                var salary = $('#salary').val()
                //1.2 生成对应的<tr>标签,并插入tbody中
                    $('<tr></tr>')
                    .append('<td>'+name+'</td>')
                    .append('<td>'+email+'</td>')
                    .append('<td>'+salary+'</td>')
                    .append('<td><a href="#" id="'+Date.now()+'">Delete</a></td>')
                    .appendTo('tbody')
                    .find('a')
                    .click(clickDelete)
                //1.3清除输入数据
                $name = $('')
                $email = $('')
                $salary = $('')
            })
            //2.删除
            //给所有的删除链接绑定点击监听
            $('a').click(clickDelete)
            
            function clickDelete(){
              var $tr= $(this).parent().parent()
              var name=$tr.children(':first').html()
              if(confirm('确定删除'+name+'吗?')){
                  $tr.remove()
              }

            }
        })
    </script>
</head>

<body>
    <table border="1px solid black" cellspacing=0>
        <thead>
            <tr>
                <td>Name</td>
                <td>Email</td>
                <td>Salary</td>
                <td></td>

            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tom</td>
                <td>tom@tom.com</td>
                <td>5000</td>
                <td><a href="#" id="001">Delete</a></td>
            </tr>
            <tr>
                <td>Jerry</td>
                <td>jerry@sohu.com</td>
                <td>8000</td>
                <td><a href="#" id="002">Delete</a></td>
            </tr>
            <tr>
                <td>Bob</td>
                <td>bob@tom.com</td>
                <td>10000</td>
                <td><a href="#" id="002">Delete</a></td>
            </tr>
        </tbody>
    </table>
    <div>
        <h2>添加新员工</h2>
        name: <input type="text" id="name"><br>
        email: <input type="text" id="email"><br>
        Salary:<input type="text" id="salary">
        <br>
        <input type="submit" value="Submit" id="submit">

    </div>
</body>

</html>

使用delegate

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table,
        div {
            margin: 30px auto;
        }

        table {
            text-align: center;
        }

        thead tr {
            font-weight: bolder;
        }

        div {
            border: 1px solid black;
            width: 300px;
            height: 200px;
            padding-left: 10px;
        }

        #submit {
            display: block;
            margin: 10px auto;
        }

        #name,
        #email,
        #salary {
            width: 230px;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {


            //1.添加
            $('#submit').click(function () {
                //1.1 收集输入的数据
                var $name = $('#name')
                var $email = $('#email')
                var $salary = $('#salary')
                var name = $('#name').val()
                var email = $('#email').val()
                var salary = $('#salary').val()
                //1.2 生成对应的<tr>标签,并插入tbody中
                    $('<tr></tr>')
                    .append('<td>'+name+'</td>')
                    .append('<td>'+email+'</td>')
                    .append('<td>'+salary+'</td>')
                    .append('<td><a href="#" id="'+Date.now()+'">Delete</a></td>')
                    .appendTo('tbody')
                    // .find('a')
                    // .click(clickDelete)
                //1.3清除输入数据
                $name = $('')
                $email = $('')
                $salary = $('')
            })
            //2.删除
            //给所有的删除链接绑定点击监听
            // $('a').click(clickDelete)
            $('tbody').delegate('a','click',clickDelete)
            
            function clickDelete(){
              var $tr= $(this).parent().parent()
              var name=$tr.children(':first').html()
              if(confirm('确定删除'+name+'吗?')){
                  $tr.remove()
              }

            }
        })
    </script>
</head>

<body>
    <table border="1px solid black" cellspacing=0>
        <thead>
            <tr>
                <td>Name</td>
                <td>Email</td>
                <td>Salary</td>
                <td></td>

            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tom</td>
                <td>tom@tom.com</td>
                <td>5000</td>
                <td><a href="#" id="001">Delete</a></td>
            </tr>
            <tr>
                <td>Jerry</td>
                <td>jerry@sohu.com</td>
                <td>8000</td>
                <td><a href="#" id="002">Delete</a></td>
            </tr>
            <tr>
                <td>Bob</td>
                <td>bob@tom.com</td>
                <td>10000</td>
                <td><a href="#" id="002">Delete</a></td>
            </tr>
        </tbody>
    </table>
    <div>
        <h2>添加新员工</h2>
        name: <input type="text" id="name"><br>
        email: <input type="text" id="email"><br>
        Salary:<input type="text" id="salary">
        <br>
        <input type="submit" value="Submit" id="submit">

    </div>
</body>

</html>

4.11 事件处理

  1. 点击响应方法①$().click();②$().on():编码不方便,可以添加多个监听,且更普遍。
  2. 事件解绑:off(eventName).
  3. 事件的坐标:
    1. event.offsetX,event.offsetY 相对于视口的左上角
    2. event.clientX,event.clientY 原点为窗口的左上角

    3. event.pageX,event.pageY  原点为页面的左上角

  4. 事件相关处理:
    1. 停止事件冒泡: event.stopPropagation()
    2. 阻止事件默认行为: event.preventDefault()

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #div1 {
            background-color: blue;
            width: 200px;
            height: 200px;
            /* 解决子元素margin对父元素的影响 */
            overflow: hidden;

        }

        #div2 {
            background-color: red;
            width: 100px;
            height: 100px;
            margin-top: 10px;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {
            //1. 给.out绑定点击监听(用两种方法绑定)
            /*  $('#div1').click(function(){
                console.log('click out')
             }) */

              $('#div1').on('click',function(){//该方法更通用
                 console.log(' on click out')
              })

            //2. 给.inner绑定鼠标移入和移出的事件监听(用3种方法绑定)
              $('#div2').mouseenter(function(){
                  console.log('鼠标移入啦!!')
              })
              $('#div2').mouseleave(function(){
                  console.log('鼠标移出啦!!')
              })

            /*  $('#div2').on('mouseenter',function(){
                 console.log('鼠标移入啦!!')
             })
             $('#div2').on('mouseleave',function(){
                 console.log('鼠标移出啦!!')
             }) */

            /*  $('#div2').hover(function(){
                console.log('鼠标移入啦!!')

             },function(){
                console.log('鼠标移出啦!!')

             }) */

            //3. 点击btn1解除.inner上所有的事件监听
             /* $('.btn1').click(function(){
                 $('#div2').off()
             }) */
            //4. 点击btn2解除.inner上的mouseenter事件
            $('.btn2').click(function(){
                 $('#div2').off('mouseenter')
             })
            //5. 点击btn3得到事件坐标
            $('.btn3').click(function(event){//event事件对象
                 console.log(event.offsetX,event.offsetY)//原点为事件元素的左上角
                 console.log(event.clientX,event.clientY)//原点为窗口的左上角
                 console.log(event.pageX,event.pageY)//原点为页面的左上角

             })
            //6. 点击.inner区域,外部点击监听不响应
            $('#div2').click(function(event){
                //停止事件冒泡
                event.stopPropagation()
            })
            //7. 点击链接,如果当前时间是偶数不跳转
            $('a').click(function(event){
                if(Date.now()%2===0){
                    event.preventDefault()
                }


            })
        })
    </script>
</head>

<body>
    <div id="div1">
        <div id="div2">
            内部div
        </div>
    </div>
    <br>
    <button class="btn1">取消绑定所有事件</button>
    <button class="btn2">取消绑定mouseenter事件</button>
    <button class="btn3">测试事件坐标</button>
    <a href="https://www.baidu.com/">百度一下</a>
</body>

</html>

 4.12 事件面试题

1. 区别mouseover与mouseenter?

答:mouseover:在移入子元素时也会触发,对应mouseout;

        mouseenter:只在移入当前元素时才会触发,对应mouseleave;

                            hover()使用的就是mouseenter()和mouseleave()。

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #div1,#div3{
            width: 200px;
            height: 200px;

        }
        #div2,#div4{
            width: 100px;
            height: 100px;
        }
        #div1{
            background-color: rgb(134, 122, 122);
        }
        #div2{
            background-color: red;

        }
        #div3{
            position: absolute;
            left: 220px;
            top: 0;
            background-color: rgb(209, 201, 201);
        }
        #div4{
            background-color: yellow;
        }
      
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function(){
            // $('#div1')
            // .mouseover(function(){
            //     console.log('mouseover 进入')
            // })
            // .mouseout(function(){
            //     console.log('mouseout 移出')

            // })
            // $('#div3')
            // .mouseenter(function(){
            //     console.log('mouseenter 进入')
            // })
            // .mouseleave(function(){
            //     console.log('mouseleave 移出')

            // })
          
        })
    </script>
</head>
<body>
    <div id="div1">div1……
        <div id="div2">
            div2……
        </div>
    </div>
    <div id="div3">
        div3……
        <div id="div4">
            div4……
        </div>
    </div>
</body>
</html>

4.13 事件委托(子元素事件交由父元素处理)

  1.  事件委托(委派/代理):

    1. 将多个子元素(li)的事件监听委托给父辈元素(ul)处理;

    2. 监听回调是加在了父辈元素上;

    3. 当操作任何一个子元素(li)时,事件会冒泡到父辈元素(ul);

    4. 父辈元素不会直接处理事件,而是根据event.target得到发生事件的子元素(li),通过这个子元素调用回调函数。

  2. 事件委托的2方

    1. 委托方:业主 li

    2. 被委托方:中介 ul

  3. 使用事件委托的好处:

    1. 添加新的子元素,自动有事件响应处理;

    2. 减少事件监听的数量:n==>1

  4. jQuery的事件委托API

    1. 设置事件委托: $(parentSelector).delegate(childrenSelector,eventName,callback)

    2. 移除事件委托: $(parentSelector).undelegate(eventName)

儿子的零花钱来自父亲(儿子委托父亲给钱),父亲通过查看儿子银行卡余额来查看儿子是否缺钱(监听),发现没有钱后,父亲通过转账(回调函数)给儿子打钱,结果儿子有钱花啦。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function(){
            //1. 点击li背景就会变红色
            //2. 点击btn 就添加一个li

            //该方法在新增li后点击该li不会变红
            // $('ul>li').click(function(){
            //     $('ul>li').css('background','red')
            // })
            // $('#btn').click(function(){
            //     $('ul').append('<li>新增的li</li>')
            // })

            $('ul').delegate('li','click',function(){
                this.style.background="red"
            })
            $('#btn').click(function(){
                $('ul').append('<li>新增的li</li>')
            })
            $('#btn2').click(function(){
                $('ul').undelegate('click')
            })
        })
    </script>
</head>
<body>
    <ul>
        <li>11111</li>
        <li>11111111</li>
        <li>111111111111</li>
        <li>111111111111111</li>
    </ul>
    <li>22222</li>
    <br>
    <button id="btn">添加新的li</button>
    <button id="btn2">移出事件委托</button>
    <br>
</body>
</html>

4.14 内置动画

淡入淡出:不断改变元素的透明度来实现的 

  1. fadeIn():带动画的显示。
  2. fadeOut():带动画隐藏。
  3. fadeToggle():带动画切换显示/隐藏。

滑动动画:不断改变元素的高度实现

  1. slideDown():带动画的展开。
  2. slideUp():带动画的收缩。
  3. slideToggle():带动画的切换展开/收缩。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .div1 {
            width: 200px;
            height: 200px;
            background-color: red;
            margin-bottom: 10px;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {
            /* 
                1.点击btn1,慢慢淡出
                    无参
                    有参
                        字符串参数
                        数字参数
                2. 点击btn2,慢慢淡入
                3. 点击btn3,淡入/淡出切换,动画结束时提示‘动画结束啦’
            */
           var $div1=$('.div1')
            $('#btn1').click(function () {
                $div1.fadeOut(1000,function(){
                    alert('动画完成啦')
                })
            })
            $('#btn2').click(function () {
                $div1.fadeIn()
            })
            $('#btn3').click(function () {
                $div1.fadeToggle()
            })
            $('#btn4').click(function () {
                $div1.slideUp()
            })
            $('#btn5').click(function () {
                $div1.slideDown()
            })
            $('#btn6').click(function () {
                $div1.slideToggle()
            })
        })
    </script>
</head>

<body>
    <div class="div1"></div>
    <button id="btn1">慢慢淡出</button>
    <button id="btn2">慢慢淡入</button>
    <button id="btn3">淡出/淡入切换</button><br>
    <button id='btn4'>慢慢收缩</button>
    <button id='btn5'>慢慢展开</button>
    <button id='btn6'>收缩/展开切换</button>
</body>

</html>

显式隐藏,默认没有动画。

  1. show():(不)带动画的显示。
  2. hide():(不)带动画的隐藏。
  3. toggle():(不)带动画的切换显示/隐藏。

 

 4.15 自定义动画练习

jQuery动画本质:在指定时间内不断通过改变元素样式值来实现的。

  1. animate():自定义动画效果的动画。
  2. stop():停止动画。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .div1 {
            position: absolute;
            width: 100px;
            height: 100px;
            top: 50px;
            left: 300px;
            background-color: red;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {
            var $div1 = $('.div1')
            //1. 逐渐扩大
            $('#btn1').click(function () {
              /*   $div1.animate({
                    width: 200,
                    height: 200
                }, 1000) */

                //先扩大宽,再扩大高
                $div1.animate({
                        width: 200
                    })
                    .animate({
                        height: 200
                    })
            })
            //2. 移动到指定位置
            $('#btn2').click(function () {
                /* $div1.animate({
                    left:500,
                    top:100
                },1000) */
                $div1.animate({
                    left:100,
                    top:20
                },1000) 

                
            })

           //移动指定的距离 (100,50)
            $('#btn3').click(function () {
                $div1.animate({
                    left:'+=100',
                    top:'+=50'
                },10000) 
            })

            //停止动画
            $('#btn4').click(function () {
                $div1.stop()
            })
        })
    </script>
</head>

<body>
    <button id="btn1">逐渐扩大</button>
    <button id="btn2">移动到指定位置</button>
    <button id="btn3">移动指定距离</button>
    <button id="btn4">停止动画</button>
    <div class="div1">阿萨德发</div>
</body>

</html>

 导航栏展开练习

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        a {
            text-decoration: none;
            color: black;
        }

        li {
            list-style: none;
            margin: 15px;

        }
        #div1{
            width: 500px;
            height: 50px;
            margin-left: 30px;
            background-color: rgb(219, 197, 240);
        }

        .first {
            float: left;
            position: relative;
        }

        
        .one,
        .two,
        .three {
            display: none;

        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        $(function () {
            var $first = $('ul>.first')
            var $revFirst = $('li').not('.first')

            $first.hover(function () {
                //实现点击.first显示子内容
                var $left=$(this).position().left//测量.first距离左侧的距离
                $(this).next().slideDown(1000).css({
                    //动画展开  
                    display:'block',
                    position: 'absolute',
                    top: '50px',
                    left:$left,
                    background:' rgb(219, 197, 240)'
                    
                })
                
            },function(){
                $(this).next().css('display','none')
            })
        })
    </script>
</head>

<body>
    <div id="div1">
        <ul>
            <li class="first"><a href="javascript:;">王者荣耀</a></li>
        </ul>
        <ul>

            <li class="first"><a href="javascript:;">上路</a></li>
            <div class="one">
                <li><a href="javascript:;">亚瑟</a></li>
                <li><a href="javascript:;">夏侯惇</a></li>
                <li><a href="javascript:;">白起</a></li>
            </div>
        </ul>
        <ul>
            <li class="first "><a href="javascript:;">中路</a></li>
            <div class="two">
                <li><a href="javascript:;">妲己</a></li>
                <li><a href="javascript:;">甄姬</a></li>
                <li><a href="javascript:;">小乔</a></li>
            </div>
        </ul>
        <ul>
            <li class="first "><a href="javascript:;">下路</a></li>
            <div class="three">
                <li><a href="javascript:;">鲁班七号</a></li>
                <li><a href="javascript:;">虞姬</a></li>
                <li><a href="javascript:;">后羿</a></li>
            </div>
        </ul>
        <ul>
            <li class="first "><a href="javascript:;">一起开黑</a></li>
        </ul>
    </div>
</body>

</html>

 4.16 多库共存

问题: 如果有2个库都有$,就存在冲突。

解决: jQuery库可以释放$的使用权,让另一个库可以正常使用,此时jQuery库就只能使用jQuery了 

API:  jQuery.noConflict()

自定义js文件

(function(){
    window.$=function(){
        console.log('my lib......')
    }
})()

 html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../jQuery/js/lib.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
        //释放$的使用权
        jQuery.noConflict()
        //调用lib中的$
        $()
        //要想使用jQuery的功能,只能使用jQuery
        jQuery(function(){
            console.log('文档加载完成')

        })
        console.log('+++++')
    </script>
</head>
<body>
  
    
</body>
</html>

 4.17 区别onload与ready

 区别:window.onload与$(document).ready()

(1)window.onload:

    包括页面的图片加载完成后才会回调(晚)

   只能有一个监听回调

(2) $(document).ready()

    等同于$(function(){})

    页面加载完成就回调(早)

    可以有多个监听回调

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script>
    /*
      
        区别:window.onload与$(document).ready()
            window.onload:
                包括页面的图片加载完成后才会回调(晚)
                只能有一个监听回调
            $(document).ready()
                等同于$(function(){})
                页面加载完成就回调(早)
                可以有多个监听回调
     */
        console.log('直接'+ $('#img').width())
        $(function(){
        console.log('ready'+$('#img').width())
            
        })//0
        $(function(){
        console.log('ready2'+$('#img').width())
            
        })
        window.onload=function(){
        console.log('onload'+$('#img').width())
    
        }//500
        window.onload=function(){
        console.log('onload2'+$('#img').width())
    
        }
           
    </script>
</head>
<body>
    <img id='img'src="https://c-ssl.duitang.com/uploads/item/202007/07/20200707163015_hyfiy.thumb.1000_0.jpg" alt="">
</body>

</html>

 

5. jQuery插件

5.1 jQuery自定义插件

  1. 扩展jQuery的工具方法。
    1. $.extend(object)
  2. 扩展jQuery对象的方法。
    1. $.fn.extend(object)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.1/jquery.js"></script>
    <script src="../jQuery/js/my_plugin.js"></script>
   
</head>
<body>
     你爱好的运动是?
    <input type="checkbox" name="select" id="checkedAllBox" >全选/全不选
    <br>
    <input type="checkbox" value="football" name="items">足球
    <input type="checkbox" value="basketball" name="items" >篮球
    <input type="checkbox" value="badminton" name="items">羽毛球
    <input type="checkbox" value="table-tennis" name="items">乒乓球
    <br>
    <input type="submit" value="全选" id="checkedAllBtn">
    <input type="submit" value="全不选" id="checkedNoBtn">
    <input type="submit" value="反选" id="checkedRevBtn">
    <input type="submit" value="提交" id="sendBtn">
</body>
<script>
    $(function(){
      console.log($.min(3,5),$.max(3,5))
      var str='    王者荣耀   '
      console.log('------'+$.leftTrim(str)+'------')
      console.log('------'+$.rightTrim(str)+'------')
      var $items=$(':checkbox[name=items]')
      $('#checkedAllBox').click(function(){
          alert('hi')
          $items.checkAll()
      })
      $('#checkedNoBtn').click(function(){
          $items.unCheckAll()
      })
      $('#checkedRevBtn').click(function(){
          $items.reverseCheck()
      })
    })

  </script>
</html>

5.2 jQuery插件

  1.  jQuery-validation:表单验证。

  2. jQuery UI:各种小插件的集合体。

  3. laydate:日期控件(不是jQuery插件)。

1. jQuery-validation

(1) 下载validation:https://jqueryvalidation.org/

(2)使用插件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .error{
            color: red;
        }
    </style>
    <script src="../jquery-validation-1.19.2/lib/jquery.js"></script>    
    <script src="../jquery-validation-1.19.2/dist/jquery.validate.js"></script>
    <script>
        $(function(){
            //声明式验证

            //对表单开启验证
            $('#myForm').validate({
                messages:{
                    username:{
                        required:'用户名是必须的',
                        minlength:'用户名最小为6位',
                    },
                    pwd1:{
                        required:'密码是必须的',
                        minlength:'用密码最小为6位',
                        maxlength:'密码最多为8位'
                    },
                    pwd2:'必须与密码相同'
                }
            })
        })
    </script>
</head>
<body>
    <form action="xxx" id="myForm">
        <p>用户名<input type="text" name="username" required minlength="6"></p>
        <p>密码<input type="password" name="pwd1"id="password" required minlength="6" maxlength="8"></p>
        <p>确认密码<input type="password" name="pwd2" equalTo="#password"></p>
        <p><input type="submit" value="注册"></p>

    </form>
</body>
</html>

 

2. jQuery UI

(1)下载:http://www.121down.com/soft/softview-42812.html#downaddress

(2) 代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../jquery-ui-1.11.4/jquery-ui.css">
    <script src="../jquery-ui-1.11.4/external/jquery/jquery.js"></script>
    <script src="../jquery-ui-1.11.4/jquery-ui.js"></script>
    <script>
        $(function () {
                    //1.手风琴
                    $('#accordion').accordion()
                    //所有数据的数据
                    var availableTags = [
                        "ActionScript",
                        "AppleScript",
                        "Asp",
                        "BASIC",
                        "C",
                        "C++",
                        "Clojure",
                        "COBOL",
                        "ColdFusion",
                        "Erlang",
                        "Fortran",
                        "Groovy",
                        "Haskell",
                        "Java",
                        "JavaScript",
                        "Lisp",
                        "Perl",
                        "PHP",
                        "Python",
                        "Ruby",
                        "Scala",
                        "Scheme"
                    ];
                    //2.自动搜索匹配
                    $("#autocomplete").autocomplete({
                        source: availableTags //数据源
                    });
                    //3.选项卡
                    $('#tabs').tabs()
                })
    </script>
</head>

<body>
    <!-- Accordion:手风琴 -->
    <h2 class="demoHeaders">1. Accordion</h2>
    <div id="accordion">
        <h3>First</h3>
        <div>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</div>
        <h3>Second</h3>
        <div>Phasellus mattis tincidunt nibh.</div>
        <h3>Third</h3>
        <div>Nam dui erat, auctor a, dignissim quis.</div>
    </div>

    <!-- Autocomplete -->
    <h2 class="demoHeaders">Autocomplete</h2>
    <div>
        <input id="autocomplete" title="type &quot;a&quot;">
    </div>
    <!-- Tabs:选项卡 -->
    <h2 class="demoHeaders">Tabs</h2>
    <div id="tabs">
        <ul>
            <li><a href="#tabs-1">First</a></li>
            <li><a href="#tabs-2">Second</a></li>
            <li><a href="#tabs-3">Third</a></li>
        </ul>
        <div id="tabs-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
            aliquip ex ea commodo consequat.</div>
        <div id="tabs-2">Phasellus mattis tincidunt nibh. Cras orci urna, blandit id, pretium vel, aliquet ornare,
            felis. Maecenas scelerisque sem non nisl. Fusce sed lorem in enim dictum bibendum.</div>
        <div id="tabs-3">Nam dui erat, auctor a, dignissim quis, sollicitudin eu, felis. Pellentesque nisi urna,
            interdum eget, sagittis et, consequat vestibulum, lacus. Mauris porttitor ullamcorper augue.</div>
    </div>
</body>

</html>

 

 

3. laydate

(1)下载:https://www.layui.com/laydate/

(2)代码: 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            padding: 20px;
        }

        .demo-input {
            padding-left: 10px;
            height: 38px;
            min-width: 262px;
            line-height: 38px;
            border: 1px solid #e6e6e6;
            background-color: #fff;
            border-radius: 2px;
        }
    </style>
    <script src="../layDate-v5.0.9/laydate/laydate.js"></script>
    <script>
        lay('#version').html('-v' + laydate.v);

        //执行一个laydate实例
        laydate.render({
            elem: '#test1' //指定元素
        });
    </script>
</head>

<body>
    <input type="text" class="demo-input" placeholder="请选择日期" id="test1">

</body>

</html>

 

 

6. 练习

 

 

jQuery是一个JavaScript库,用于简化HTML文档的操作、事件处理、动画效果和Ajax等功能。如果你想从入门精通jQuery,可以按照以下步骤进行学习: 1. 学习基础知识:了解jQuery的基本语法、选择器和常用方法。可以通过官方文档、在线教程或书籍来学习。掌握jQuery的选择器语法,可以通过CSS选择器选取HTML元素,并使用jQuery提供的方法对其进行操作。 2. 实践编程:通过实际编写jQuery代码来加深理解。可以尝试使用jQuery来处理表单验证、DOM操作、事件绑定等常见任务。同时,结合HTML和CSS来创建一些简单的交互效果,如点击展开、淡入淡出等。 3. 深入学习特性:学习jQuery的高级特性,如动画效果、Ajax请求和响应处理等。掌握这些特性可以为你的Web开发提供更多可能性。使用jQuery内置的动画方法可以创建各种各样的动态效果。了解如何使用Ajax来实现与服务器的数据交互,以及如何处理服务器返回的数据。 4. 拓展知识:了解jQuery的插件和扩展。jQuery拥有庞大的插件生态系统,可以帮助你快速实现各种功能,如图片轮播、日期选择器、表格排序等。掌握如何使用插件可以提高你的开发效率和质量。 5. 实践项目:尝试实践一些小型项目或参与开源项目,将所学的知识应用到实际开发中。通过项目实践,你可以更好地理解jQuery的应用场景和优势,并锻炼自己的编程能力。 总之,学习jQuery需要不断的实践和积累经验。通过不断学习和实践,你可以逐步掌握jQuery的各项功能和技巧,从而达到精通的水平。祝你学习顺利!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值