一、jQuery是什么?

<1> jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript 高手加入其team。

<2> jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

<3> 它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器。

<4> jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。

<5> jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。

二、什么是jQuery对象?

jQuery 对象就是通过jQuery包装DOM对象后产生的对象,jQuery 对象是 jQuery 独有的。如果一个对象是 jQuery 对象, 那么它就可以使用 jQuery 里的方法:$(“#test”).html()

$("#test").html()    
       //意思是指:获取ID为test的元素内的html代码。其中html()是jQuery里的方法 

       // 这段代码等同于用DOM实现代码:document.getElementById("test").innerHTML; 

       //虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法,乱使用会报错

       //约定:如果获取的是 jQuery 对象,那么要在变量名前面加上$ 

var $variable = jQuery 对象
var variable = DOM 对象

$variable[0]:jquery对象转为dom对象      $("#msg").html() <==> $("#msg")[0].innerHTML

jQuery的基础语法:$(selector).action()

使用前需导入jQuery文件

<script src="jquery-3.3.1.js"></script>

三、寻找元素(选择器和筛选器)

3.1 选择器

3.1.1 基本选择器
$('*'):选择全部标签

$("#id"):根据id属性进行选择   

$(".class"):根据class属性选择  

$("element"):按标签类型选择

$(".class,p,div"):以上方法可以进行多项选择

注:$也可写为jQuery,例如:$('div').css('color','red')可以写为jQuery('div').css('color','red')
3.1.2 层级选择器
$('.outer p'):后代选择器,会找所有后代,包括子代,孙子代...

$('.outer>p'):子代选择器,只会找子代

$('.outer+p'):毗邻选择器,只找下面同级紧挨着的

$('.outer~p'):向下找同级所有的,不要求紧挨着
3.1.3 基本筛选器
// :代表筛选

$('li:first'):选第一个li标签

$('li:last'):选最后一个li标签

$('li:eq(1)'):选任意索引的li标签,索引从0开始

$('li:even'):选索引为偶数的li标签

$('li:odd'):选索引为奇数的li标签

$('li:gt(2)'):选第三个位置以下的li标签

$('li:lt(2)'):第三个位置以上的li标签
3.1.4 属性选择器
$('[alex]'):带有"alex"属性的全部标签

$('[alex="sb"]'):"alex"属性等于某个值的标签

$('[alex="sb"][id="p1"]'):满足多个属性的选择条件的标签
3.1.5 表单选择器   
iuput表单<input type="text">、<input type="checkbox">、<input type="submit">等,有如下选择方法:

$(':text')  //只有表单可以这么写,等同于下面的写法

$('[type="text"]')

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>hello</div>

<a href="">click</a>

<p id="p1" alex="sb">pppp</p>
<p id="p2" alex="sb">pppp</p>
<div class="outer">outer
    <div class="inner">inner
        <p>inner p</p>
    </div>
    <p>alex</p>
</div>

<p>xialv</p>
<div class="outer2">Yuan</div>
<p>xialv1</p>
<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
    <li>4444</li>
    <li>4444</li>
    <li>4444</li>
</ul>

<input type="text">
<input type="checkbox">
<input type="submit">

<script src="jquery-3.3.1.js"></script>
<script>

    // 基本选择器
    //$('div').css('color','red')    //同jQuery('div').css('color','red')
    //$('*').css('color','red')
    //$('#p1').css('color','red')
    //$('.outer').css('color','red')
    //$('.inner,p,div').css('color','red')

    // 层级选择器
    //$('.outer p').css('color','red')    //后代选择器
    //$('.outer>p').css('color','red')    //子代选择器
    //$('.outer+p').css('color','red')    //毗邻选择器,只找下面同级紧挨着的
    //$('.outer~p').css('color','red')    //向下找同级所有的

    // 基本筛选器
    //$('li:first').css('color','red')
    //$('li:last').css('color','red')
    //$('li:eq(1)').css('color','red')
    //$('li:even').css('color','red')
    //$('li:odd').css('color','red')
    //$('li:gt(2)').css('color','red')    //第三个位置以下的
    //$('li:lt(2)').css('color','red')    //第三个位置以上的

    // 属性选择器
    //$('[alex]').css('color','red')
    //$('[alex="sb"][id="p1"]').css('color','red')

    // 表单选择器
    //$('[type="text"]').css('width','200px')
    //$(':text').css('width','400px')    //只有表单可以这么写,等同于上面的写法

</script>
</body>
</html>

以上内容样例

3.2 筛选器

3.2.1  过滤筛选器
// 此筛选方法较上面的基本筛选器方法更灵活,建议使用

$('li').eq(2)   //等同于$('li:eq(2)')

$('li').first()

$('li').last()

$('div').hasClass('xx')    //判断某一个标签是否有class='xx'的属性,返回结果是true或false
查找筛选器
$('.outer').children('p'))    //只找儿子代,可以查找多种标签

$('.outer').find('p,.shade')    //儿子和孙子代都找,可以查找多种标签


$('li').eq(2).next()     //后面一个

$('li').eq(2).nextAll()    //后面全部

$('li').eq(2).nextUntil('#end')    //后面部分,不包括'#end'


$('li').eq(4).prev()    //前面一个

$('li').eq(4).prevAll()    //前面全部

$('li').eq(4).prevUntil('li:eq(0)')    //前面部分,不包括'li:eq(0)'


$('.outer .inner p').parent()    //向外找到父标签停止

$('.outer .inner p').parents()    //向外找到父标签,会继续向外无限找父标签,直到最外层的,一般不用

$('.outer .inner p').parentsUntil('body')    //向外找父标签,直到某一层,不包括该层


$('.outer').siblings().css('color','red')    //找所有的兄弟级标签

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>hello</div>

<a href="">click</a>

<p id="p1" alex="sb">pppp</p>
<p id="p2" alex="sb">pppp</p>
<div class="outer">outer
    <div class="inner">inner
        <p>inner p</p>
    </div>
    <p>alex</p>
</div>

<p>xialv</p>
<div class="outer2">Yuan</div>
<p>xialv1</p>
<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
    <li>4444</li>
    <li id="end">4444</li>
    <li>4444</li>
</ul>

<input type="text">
<input type="checkbox">
<input type="submit">

<script src="jquery-3.3.1.js"></script>
<script>
    //筛选器
    //$('li').eq(2).css('color','red');   //等同于$('li:eq(2)').css('color','red'),比此方法灵活
    //$('li').first().css('color','red');
    //$('li').last().css('color','red')

    //查找筛选器
    //子代
    //$('.outer').children('p').css('color','red')    //只找儿子代
    //$('.outer').find('p').css('color','red')    //儿子和孙子代都找

    //$('li').eq(2).next().css('color','red')     //后面一个
    //$('li').eq(2).nextAll().css('color','red')    //后面全部
    //$('li').eq(2).nextUntil('#end').css('color','red')    //后面部分

    //$('li').eq(4).prev().css('color','red')
    //$('li').eq(4).prevAll().css('color','red')
    //$('li').eq(4).prevUntil('li:eq(0)').css('color','red')

    //console.log($('.outer .inner p').parent().html())
    //$('.outer .inner p').parents().css('color','red')
    //$('.outer .inner p').parentsUntil('body').css('color','red')

    $('.outer').siblings().css('color','red')

</script>
</body>
</html>

以上内容样例

  • 实例之左侧菜单

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .outer{
            height:1000px;
            width:100%;
        }
        .menu{
            float:left;
            background-color: beige;
            width:30%;
            height:500px;
        }
        .content{
            float:left;
            background-color: rebeccapurple;
            width:70%;
            height:500px;
        }
        .title{
            background-color: aquamarine;
            line-height: 40px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>

<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title" onclick="show(this)">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>

        <div class="item">
            <div class="title" onclick="show(this)">菜单二</div>
            <div class="con hide">
                <div>222</div>
                <div>222</div>
                <div>222</div>
            </div>
        </div>

        <div class="item">
            <div class="title" onclick="show(this)">菜单三</div>
            <div class="con hide">
                <div>333</div>
                <div>333</div>
                <div>333</div>
            </div>
        </div>
    </div>
    <div class="content"></div>
</div>


<script src="jquery-3.3.1.js"></script>
<script>
    function show(self){
        $(self).next().removeClass('hide');
        $(self).parent().siblings().children('.con').addClass('hide');
    }
</script>
</body>
</html>

View Code

四、操作元素(属性,css,文档处理)

4.1 属性操作

--------------------------属性
$("").attr();    自建属性最好用attr
$("").removeAttr();
$("").prop();    固有属性最好用prop
$("").removeProp();
--------------------------CSS类
$("").addClass([class|fn])
$("").removeClass([class|fn])

注:支持链式操作,$("").parent().addClass("hide").prev().addClass("hide")

--------------------------HTML代码/文本/值
$("").html([val|fn])    有标签样式
$("").text([val|fn])    纯文本内容
$("").val([val|fn|arr])    只限固有属性里有value的才能使用

注:html()、text()和val()的括号里没有值,表示显示标签相关的内容,括号里有值表示更改标签的内容为该值

---------------------------
$("").css("color","red")
$("").css({"color":"red","background-color":"green"})

样例:

<body>
<div class="div1" con="c1"></div>

<script src="jquery-3.3.1.js"></script>
<script>
    console.log($('div').hasClass('div1'));    //判断某一个标签是否有class等于某值的属性
    console.log($('div').attr('con'));
    console.log($('div').attr('con', 'c2'));

</script>
</body>

结果为:

jquery 便利 td jquery raty_jQuery_07

 

jquery 便利 td jquery raty_jquery 便利 td_08

<body>
<div class="div1" con="c1"></div>
<input type="checkbox" checked="checked">是否可见
<input type="checkbox">是否可见


<script>

    console.log($(':checkbox:first').attr('checked'));    //attr既可以用于固有属性,也可以用于自建属性,但是处理的时候可能出现一些其他情况
    console.log($(':checkbox:last').attr('checked'));

    console.log($(':checkbox:first').prop('checked'));
    console.log($(':checkbox:last').prop('checked'));

    console.log($('div').prop('con'));
    console.log($('div').prop('class'));   //取固有属性的时候最好用prop,取自建属性最好用attr


</script>
</body>

结果为:

jquery 便利 td jquery raty_html_09

<body>
<div class="div1" con="c1"></div>
<input type="checkbox" checked="checked">是否可见
<input type="checkbox">是否可见

<input type="text" value="123">
<div value="456"></div>

<div id="id1">
    uuuuu
    <p>ppppp</p>
</div>
<script src="jquery-3.3.1.js"></script>
<script>

    console.log($('#id1').html());    //html()、text()和val()的括号里没有值,表示显示里面的内容,括号里有值表示更改里面的内容
    console.log($('#id1').text());

    console.log($('#id1').html('<h1>YUAN</h1>'));    //有标签样式的用html方法
    console.log($('#id1').text('<h1>YUAN</h1>'));    //纯文本内容的用text方法

</script>
</body>

结果为:

jquery 便利 td jquery raty_jquery 便利 td_10

 

jquery 便利 td jquery raty_jQuery_11

 

jquery 便利 td jquery raty_html_12

<body>
<div class="div1" con="c1"></div>
<input type="checkbox" checked="checked">是否可见
<input type="checkbox">是否可见

<input type="text" value="123">
<div value="456"></div>

<div id="id1">
    uuuuu
    <p>ppppp</p>
</div>
<script src="jquery-3.3.1.js"></script>
<script>

    console.log($(':text').val());
    console.log($(':text').next().val());    //val只限固有属性里有value的才行
    $(':text').val('789');

    $('div').css({'color':'red','background-color':'green'})

</script>
</body>

jquery 便利 td jquery raty_jQuery_13

 

jquery 便利 td jquery raty_css_14

 

jquery 便利 td jquery raty_jquery 便利 td_15

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="div1" con="c1"></div>
<input type="checkbox" checked="checked">是否可见
<input type="checkbox">是否可见

<input type="text" value="123">
<div value="456"></div>

<div id="id1">
    uuuuu
    <p>ppppp</p>
</div>
<script src="jquery-3.3.1.js"></script>
<script>
    console.log($('div').hasClass('div1'));    //判断某一个标签是否有class等于某值的属性
    console.log($('div').attr('con'));
    console.log($('div').attr('con', 'c2'));

    console.log($(':checkbox:first').attr('checked'));    //attr既可以用于固有属性,也可以用于自建属性,但是处理的时候可能出现一些其他情况
    console.log($(':checkbox:last').attr('checked'));

    console.log($(':checkbox:first').prop('checked'));
    console.log($(':checkbox:last').prop('checked'));

    console.log($('div').prop('con'));
    console.log($('div').prop('class'));   //取固有属性的时候最好用prop

    console.log($('#id1').html());
    console.log($('#id1').text());
    console.log($('#id1').html('<h1>YUAN</h1>'));
    console.log($('#id1').text('<h1>YUAN</h1>'));

    //固有属性
    console.log($(':text').val());
    console.log($(':text').next().val());    //val只限固有属性里有value的才行
    $(':text').val('789');

    $('div').css({'color':'red','background-color':'green'})

</script>
</body>
</html>

以上内容样例

 jQuery循环方式
  •  支持js的循环方式:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>1111</p>
<p>2222</p>
<p>3333</p>

<script src="jquery-3.3.1.js"></script>

<script>
    arr=[11,22,33];

    for(var i=0;i<arr.length;i++){
        $('p').eq(i).html(arr[i])
    }

</script>
</body>
</html>

结果为:

jquery 便利 td jquery raty_css_18

  •  方式一:jQuery对于数组形式的循环
<script src="jquery-3.3.1.js"></script>

<script>
    arr=[11,22,33];

    //方式一
    $.each(arr,function(x,y){
        console.log(x);
        console.log(y);
    });

    // 一个参数取的是索引
    $.each(arr,function(x){
        console.log(x);
    });

</script>

结果为:

jquery 便利 td jquery raty_jQuery_19

  •  方式二:jQuery对于标签的循环
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>1111</p>
<p>2222</p>
<p>3333</p>

<script src="jquery-3.3.1.js"></script>

<script>

    //方式二
    $('p').each(function () {
        console.log($(this));    //$(this)代指当前循环的标签对象
        $(this).html('hello')
    })

</script>
</body>
</html>

结果为:

jquery 便利 td jquery raty_html_20

 

jquery 便利 td jquery raty_jquery 便利 td_21

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>1111</p>
<p>2222</p>
<p>3333</p>

<script src="jquery-3.3.1.js"></script>

<script>
    arr=[11,22,33];

    // for(var i=0;i<arr.length;i++){
    //     $('p').eq(i).html(arr[i])
    // }

    //方式一
    $.each(arr,function(x,y){
        console.log(x);
        console.log(y);
    });

    //方式二
    $('p').each(function () {
        console.log($(this));    //$(this)代指当前循环的标签对象
        $(this).html('hello')
    })



</script>



</body>
</html>

以上内容样例

实例之全反选

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

     <button onclick="selectall();">全选</button>
     <button onclick="cancel();">取消</button>
     <button onclick="reverse();">反选</button>

     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
         </tr>
     </table>

<script src="jquery-3.3.1.js"></script>
<script>
    function selectall(){
        $(':checkbox').each(function(){
            $(this).prop('checked',true)
        })
    }

    function cancel(){
        $(':checkbox').each(function(){
            $(this).prop('checked',false)
        })
    }

    function reverse(){
        $(':checkbox').each(function(){
            if($(this).prop('checked')){
                $(this).prop('checked',false)
            }
            else{
                $(this).prop('checked',true)
            }
        })
    }
</script>
</body>
</html>

View Code

实例之模态对话框

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .back{
            background-color: rebeccapurple;
            height: 2000px;
        }

        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left:0;
            right: 0;
            background-color: coral;
            opacity: 0.4;
        }

        .hide{
            display: none;
        }

        .models{
            position: fixed;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
            height: 200px;
            width: 200px;
            background-color: gold;

        }
    </style>
</head>
<body>
<div class="back">
    <input id="ID1" type="button" value="click" onclick="action1(this)">
</div>

<div class="shade hide"></div>
<div class="models hide">
    <input id="ID2" type="button" value="cancel" onclick="action2(this)">
</div>


<script src="jquery-3.3.1.js"></script>
<script>

    function action1(self){
        $(self).parent().siblings().removeClass("hide");

    }
    function action2(self){
        //$(self).parent().parent().children(".models,.shade").addClass("hide")

        // $(self).parent().addClass('hide')
        // $(self).parent().prev().addClass('hide')

        $(self).parent().addClass("hide").prev().addClass("hide")

    }
</script>
</body>
</html>

View Code

4.2 文档处理

//创建一个标签对象
    $("<p>")  或  $("<h1></h1>")


//内部插入

    $("").append(content|fn)      ----->$("p").append("<b>Hello</b>");
    $("").appendTo(content)       ----->$("p").appendTo("div");
    $("").prepend(content|fn)     ----->$("p").prepend("<b>Hello</b>");
    $("").prependTo(content)      ----->$("p").prependTo("#foo");

//外部插入

    $("").after(content|fn)       ----->$("p").after("<b>Hello</b>");
    $("").before(content|fn)      ----->$("p").before("<b>Hello</b>");
    $("").insertAfter(content)    ----->$("p").insertAfter("#foo");
    $("").insertBefore(content)   ----->$("p").insertBefore("#foo");

//替换
    $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>");

//删除

    $("").empty()
    $("").remove([expr])

//复制

    $("").clone([Even[,deepEven]])

示例:

//内部插入——后面添加
 
$('.c1').append($ele);

$ele.appendTo('.c1')

结果为:

jquery 便利 td jquery raty_jquery 便利 td_28

//内部插入——前面添加

$('.c1').prepend($ele);

$ele.prependTo('.c1');

结果为:

jquery 便利 td jquery raty_jquery 便利 td_29

//外部插入——后面添加

$('.c1').after($ele);    

ele.insertAfter('.c1')

结果为:

jquery 便利 td jquery raty_jquery 便利 td_30

//外部插入——前面添加

$('.c1').before($ele)

$ele.insertBefore('.c1')

结果为:

jquery 便利 td jquery raty_jQuery_31

//替换——前面的替换为后面的

$('p').replaceWith($ele)

结果为:

jquery 便利 td jquery raty_css_32

---->

jquery 便利 td jquery raty_jQuery_33

//清空与删除

$('.c1').empty()    //清空标签里的内容,但保留标签结构

$('.c1').remove()    //删除整个标签
//clone

var $ele2=$('.c1').clone();    //clone(true):true参数代表只复制标签样式,不复制标签中的绑定事件
$('.c1').after($ele2)

结果为:

jquery 便利 td jquery raty_jquery 便利 td_34

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<div class="c1">
    <p>PPP</p>
</div>

<button>add</button>
<script src="jquery-3.3.1.js"></script>
<script>
    $('button').click(function(){
        //$('.c1').append('<h1>HELLO YUAN</h1>')

        var $ele=$('<h1>');    //$ele=$('<h1></h1>'),创建一个标签
        $ele.html('HELLO WORLD!');
        $ele.css('color','red');

        //内部插入
        //$('.c1').append($ele);
        //$ele.appendTo('.c1')

        //$('.c1').prepend($ele);
        //$ele.prependTo('.c1');

        //外部插入
        //$('.c1').after($ele);    //.c1是主语
        //$ele.insertAfter('.c1')    //.c1是主语
        //$('.c1').before($ele)//
        //$ele.insertBefore('.c1')

        //替换
        //$('p').replaceWith($ele)

        //删除与清空
        //$('.c1').empty()    //保留标签结构
        //$('.c1').remove()    //删除整个标签

        //clone
        var $ele2=$('.c1').clone()
        $('.c1').after($ele2)
    })
</script>
</body>
</html>

以上内容样例

实例之复制样式条

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div class="outer">
    <div class="item">
        <button onclick="add(this)">+</button>
        <input type="text">
    </div>
</div>


<script src="jquery-3.3.1.js"></script>
<script>
    function add(self){
        // var $clone_obj=$(".outer .item").clone();  // 用这种方法会一遍二,二变四的增加

        var $clone_obj=$(self).parent().clone();
        $clone_obj.children('button').html('-').attr('onclick','remove_obj(this)');

        $('.outer').append($clone_obj)
    }

    function remove_obj(self){
        $(self).parent().remove()
    }

</script>
</body>
</html>

View Code

4.3 css操作

$("").css(name|pro|[,val|fn])

位置
$("").offset([coordinates])
$("").position()
$("").scrollTop([val])
$("").scrollLeft([val])

尺寸
$("").height([val|fn])
$("").width([val|fn])
$("").innerHeight()
$("").innerWidth()
$("").outerHeight([soptions])
$("").outerWidth([options])
  •  offset:相对于视口的偏移量(窗口的最左上角)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        *{
            margin:0px;
            padding:0px;
        }
        .div1,.div2{
            width:200px;
            height:100px;
        }
        .div1{
            border:5px solid rebeccapurple;
            padding:20px;
            margin:2px;
            background-color: antiquewhite;
        }
        .div2{
            background-color: rebeccapurple;
        }

        .outer{
            position:relative;
        }
    </style>
</head>
<body>

<div class="div1"></div>

<div class="outer">
    <div class="div2"></div>
</div>

<script src="jquery-3.3.1.js"></script>
<script>

    //offset():相对于视口的偏移量
    console.log($('.div1').offset().top);
    console.log($('.div1').offset().left);

    console.log($('.div2').offset().top);
    console.log($('.div2').offset().left);

</script>
</body>
</html>

结果为:

jquery 便利 td jquery raty_jQuery_39

  •  position:相对于已经定位的父标签的偏移量
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        *{
            margin:0px;
            padding:0px;
        }
        .div1,.div2{
            width:200px;
            height:100px;
        }
        .div1{
            border:5px solid rebeccapurple;
            padding:20px;
            margin:2px;
            background-color: antiquewhite;
        }
        .div2{
            background-color: rebeccapurple;
        }

        .outer{
            position:relative;
        }
    </style>
</head>
<body>

<div class="div1"></div>

<div class="outer">
    <div class="div2"></div>
</div>

<script src="jquery-3.3.1.js"></script>
<script>
sole.log($('.div2').offset().left);

    //position():相对于已经定位的父标签的偏移量
    console.log($('.div1').position().top);
    console.log($('.div1').position().left);

    console.log($('.div2').position().top);
    console.log($('.div2').position().left);

</script>
</body>
</html>

结果为:

jquery 便利 td jquery raty_css_40

  • height:内容区的高度
  • innerHeight:height+padding
  • outerHeight:height+padding+border
  • outerHeight(True):height+padding+border+margin
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        *{
            margin:0px;
            padding:0px;
        }
        .div1,.div2{
            width:200px;
            height:100px;
        }
        .div1{
            border:5px solid rebeccapurple;
            padding:20px;
            margin:2px;
            background-color: antiquewhite;
        }
        .div2{
            background-color: rebeccapurple;
        }

        .outer{
            position:relative;
        }
    </style>
</head>
<body>

<div class="div1"></div>

<div class="outer">
<div class="div2"></div>
</div>

<script src="jquery-3.3.1.js"></script>
<script>

    console.log($('.div1').height());
    console.log($('.div1').innerHeight());    // 加上padding
    console.log($('.div1').outerHeight());    // 加上padding和border
    console.log($('.div1').outerHeight(true));    // 加上padding、border和margin
    console.log($('.div1').height('300px'));    // 赋值

</script>
</body>
</html>

结果为:

jquery 便利 td jquery raty_css_41

  • scrollTop:纵向滑轮相对于视口顶部的位置,scrollLeft:横向滑轮相对于视口左边的位置

$(window).scrollTop():滑轮距离最顶端的位置,$(window).scrollTop(100):调整滑轮到距离最顶端100像素的位置......

jquery 便利 td jquery raty_jQuery_42

监听滑轮位置:

<script src="jquery-3.3.1.js"></script>
<script>
    window.onscroll=function(){             //监听滑轮位置,只要滑轮动就执行里面的代码
        console.log($(window).scrollTop());

</script>

实例:返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin:0px;
            padding:0px;
        }
        .div2{
            width:100%;
            height:800px;
        }
        .div1{
            width:40%;
            height:150px;
            background-color: antiquewhite;
            overflow:auto;
        }
        .div2{
            background-color: rebeccapurple;
        }

        .returnTop{
            position:fixed;
            right:20px;
            bottom:20px;
            width:90px;
            height:50px;
            background-color: gray;
            color:white;
            text-align:center;
            ling-height:50px;
        }

        .hide{
            display: none;
        }
    </style>
</head>
<body>

<div class="div1">
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
</div>

<div class="div2">
    <button>return</button>
</div>

<div class="returnTop hide" onclick="returnTop()">返回顶部</div>


<script src="jquery-3.3.1.js"></script>
<script>
    window.onscroll=function(){             //监听滑轮位置,只要滑轮动就执行里面的代码
        // console.log($(window).scrollTop());
        if($(window).scrollTop()>100){
            $('.returnTop').removeClass('hide')
        }else{
            $('.returnTop').addClass('hide')
        }
    };

    function returnTop(){
        $(window).scrollTop(0)
        //$('.div1').scrollTop(0)
    }

    $('.div2 button').click(function(){
        $('.div1').scrollTop(0)
    })

</script>

</body>
</html>

五、事件

页面载入
    ready(fn)  //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
    $(document).ready(function(){}) --简写形式--> $(function(){})

事件处理
    $("").on(event,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。

    //  .on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如:
    //  $('ul').on('click', 'li', function(){console.log('click');})就是筛选出ul下的li给其绑定
    //  click事件;

    [selector]参数的好处:
        好处在于.on方法为动态添加的元素也能绑上指定事件;如:

        $('ul li').on('click', function(){console.log('click');})的绑定方式和
        $('ul li').bind('click', function(){console.log('click');})一样;
        通过js给ul添加了一个li:$('ul').append('<li>js new li<li>');
        这个新加的li是不会被绑上click事件的

        但是用$('ul').on('click', 'li', function(){console.log('click');}方式绑定,然后动态添加
        li:$('ul').append('<li>js new li<li>');这个新生成的li被绑上了click事件
    
    [data]参数可以传入事件中,进行调用:
             function myHandler(event) {
                alert(event.data.foo);
                }
             $("li").on("click", {foo: "bar"}, myHandler)
  • 事件绑定和解除绑定:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
</ul>

<button>add</button>

<script src="jquery-3.3.1.js"></script>
<script>

    //事件绑定的简写方式
     $('ul li').click(function(){
         alert(6666)
     })

    //绑定
    $('ul li').bind('click',function(){
        alert(777)
    });
//解除绑定
    $('ul li').unbind('click')


    $('button').click(function(){
            var $ele=$('<li>');
            var len=$('ul li').length;
            $ele.html((len+1)*1111);
            $('ul').append($ele)
    })

</script>
</body>
</html>
  • 事件委托:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
</ul>

<button>add</button>

<script src="jquery-3.3.1.js"></script>
<script>

    //事件委托
    $('ul').on('click','li',function(){   //给ul绑定,ul又把事件委托给li,这样ul里新加的li也可以绑定到事件
        alert(999)
    });


    $('button').click(function(){
            var $ele=$('<li>');
            var len=$('ul li').length;
            $ele.html((len+1)*1111);
            $('ul').append($ele)
    })

</script>
</body>
</html>
  • 事件准备:页面加载完之后再执行该代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script src="jquery-3.3.1.js"></script>
<script>

    //事件准备加载方式一
    //等页面加载完之后再执行代码
    $(document).ready(function(){
        $('ul li').html(5);
    });

    //事件准备加载方式二
    //等页面加载完之后再执行代码--简写
    $(function(){
        $('ul li').html(5);
    });

</script>
</head>
<body>

<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
</ul>

<button>add</button>

</body>
</html>

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script src="jquery-3.3.1.js"></script>
<script>
    //事件准备加载方式一
    //等页面加载完之后再执行代码
    $(document).ready(function(){
        $('ul li').html(5);
    });
    //事件准备加载方式二
    //等页面加载完之后再执行代码--简写
    $(function(){
        $('ul li').html(5);
    });

</script>
</head>
<body>


<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
</ul>

<button>add</button>

<script src="jquery-3.3.1.js"></script>
<script>

    //事件绑定的简写方式
    // $('ul li').click(function(){
    //     alert(6666)
    // })

    //绑定
    $('ul li').bind('click',function(){
        alert(777)
    });
    //解除绑定
    //$('ul li').unbind('click')

    //事件委托
    $('ul').on('click','li',function(){   //给ul绑定,ul又把事件委托给li,这样ul里新加的li也可以绑定到事件
        alert(999)
    });


    $('button').click(function(){
            var $ele=$('<li>');
            var len=$('ul li').length;
            $ele.html((len+1)*1111);
            $('ul').append($ele)
    })

</script>
</body>
</html>

以上内容样例

实例之面板拖动

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div style="border: 1px solid #ddd;width: 600px;position: absolute;">
        <div id="title" style="background-color: black;height: 40px;color: white;">
            标题
        </div>
        <div style="height: 300px;">
            内容
        </div>
    </div>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script>
    $(function(){
        // 页面加载完成之后自动执行
        $('#title').mouseover(function(){
            $(this).css('cursor','move');
        }).mousedown(function(e){
            //console.log($(this).offset());
            var _event = e || window.event;
            // 原始鼠标横纵坐标位置
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;

            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;

            $(this).bind('mousemove', function(e){
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;

                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);

                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');

            })
        }).mouseup(function(){
            $(this).unbind('mousemove');
        });
    })
</script>
</body>
</html>

View Code

实例之放大镜

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>bigger</title>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        .outer{
            height: 350px;
            width: 350px;
            border: dashed 5px cornflowerblue;
        }
        .outer .small_box{
            position: relative;
        }
        .outer .small_box .float{
            height: 175px;
            width: 175px;
            background-color: darkgray;
            opacity: 0.4;
            fill-opacity: 0.4;
            position: absolute;
            display: none;

        }

        .outer .big_box{
            height: 400px;
            width: 400px;
            overflow: hidden;
            position:absolute;
            left: 360px;
            top: 0px;
            z-index: 1;
            border: 5px solid rebeccapurple;
            display: none;


        }
        .outer .big_box img{
            position: absolute;
            z-index: 5;
        }


    </style>
</head>
<body>

        <div class="outer">
            <div class="small_box">
                <div class="float"></div>
                <img src="small.jpg">

            </div>
            <div class="big_box">
                <img src="big.jpg">
            </div>

        </div>


<script src="jquery-3.3.1.js"></script>
<script>

    $(function(){

          $(".small_box").mouseover(function(){

              $(".float").css("display","block");
              $(".big_box").css("display","block")

          });
          $(".small_box").mouseout(function(){

              $(".float").css("display","none");
              $(".big_box").css("display","none")

          });

          $(".small_box").mousemove(function(e){

              var _event=e || window.event;

              var float_width=$(".float").width();
              var float_height=$(".float").height();

              console.log(float_height,float_width);

              var float_height_half=float_height/2;
              var float_width_half=float_width/2;
              console.log(float_height_half,float_width_half);


               var small_box_width=$(".small_box").height();
               var small_box_height=$(".small_box").width();



//  鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
              var mouse_left=_event.clientX-float_width_half;
              var mouse_top=_event.clientY-float_height_half;

              if(mouse_left<0){
                  mouse_left=0
              }else if (mouse_left>small_box_width-float_width){
                  mouse_left=small_box_width-float_width
              }


              if(mouse_top<0){
                  mouse_top=0
              }else if (mouse_top>small_box_height-float_height){
                  mouse_top=small_box_height-float_height
              }

               $(".float").css("left",mouse_left+"px");
               $(".float").css("top",mouse_top+"px")

               var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
               var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);

              console.log(percentX,percentY)

               $(".big_box img").css("left", -percentX*mouse_left+"px")
               $(".big_box img").css("top", -percentY*mouse_top+"px")
          })
    })


</script>
</body>
</html>

View Code

六、动画效果

显示隐藏:show显示,hide隐藏,toggle切换显示和隐藏

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>hello</div>

<button onclick="f1()">显示</button>
<button onclick="f2()">隐藏</button>
<button onclick="f3()">切换</button>

<script src="jquery-3.3.1.js"></script>
<script>

    function f1(){
        $('div').show(1000,function(){
            alert('show')
        })    //毫秒
    }

    function f2(){
        $('div').hide(1000,function(){      //回调函数
            alert(1234)
        })
    }

    function f3(){
        $('div').toggle(1000)
    }
</script>
</body>
</html>

View Code

滑动:slideDown滑动显示,slideUp:滑动隐藏,slideToggle:滑动切换显示和隐藏

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
    $(document).ready(function(){
     $("#slideDown").click(function(){
         $("#content").slideDown(1000);
     });
      $("#slideUp").click(function(){
         $("#content").slideUp(1000);
     });
      $("#slideToggle").click(function(){
         $("#content").slideToggle(1000);
     })
  });
    </script>
    <style>

        #content{
            text-align: center;
            background-color: lightblue;
            border:solid 1px red;
            display: none;
            padding: 50px;
        }
    </style>
</head>
<body>

    <div id="slideDown">出现</div>
    <div id="slideUp">隐藏</div>
    <div id="slideToggle">toggle</div>

    <div id="content">helloworld</div>

</body>
</html>

View Code

淡入淡出:fadeIn淡入,fadeOut淡出,fadeToggle:淡入淡出切换,fadeTo可调节透明度的淡入

jquery 便利 td jquery raty_jquery 便利 td

jquery 便利 td jquery raty_html_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
    $(document).ready(function(){
   $("#in").click(function(){
       $("#id1").fadeIn(1000);


   });
    $("#out").click(function(){
       $("#id1").fadeOut(1000);

   });
    $("#toggle").click(function(){
       $("#id1").fadeToggle(1000);


   });
    $("#fadeto").click(function(){
       $("#id1").fadeTo(1000,0.4);

   });
});



    </script>

</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>

      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>

</body>
</html>

View Code

回调函数:在执行完某个函数之后执行的函数

<script src="jquery-3.3.1.js"></script>
<script>

        $('div').hide(1000,function(){      //回调函数
            alert(1234)
        })
    }

</script>

七、扩展方法 (插件机制)

用JQuery写插件时,最核心的两个方法:

$.extend(object)      //为JQuery 添加一个静态方法
$.fn.extend(object)   //为JQuery实例(标签)添加一个方法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>111</p>
<p>222</p>
<p>333</p>


<script src="jquery-3.3.1.js"></script>
<script>

    $.extend({
        Myprint:function(){
            console.log('hello')
        }
    });

    $.Myprint();

————————————————————————————————————————————————————————————————————————————————————————————————

    jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },    //三元运算符,如果a<b,执行a,否则执行b
          max: function(a, b) { return a > b ? a : b; }
        });

    console.log($.min(3,4));

</script>
</body>
</html>

结果为:

jquery 便利 td jquery raty_html_55

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>111</p>
<p>222</p>
<p>333</p>

<script src="jquery-3.3.1.js"></script>
<script>

    // $.fn.extend({
    //     GetText:function() {
    //         for (var i = 0; i < this.length; i++) {
    //             console.log(this[i].innerHTML)
    //         }
    //     }
    // });


    $.fn.extend({
        GetText:function(){
            $.each($(this),function(x,y) {
                // console.log(x);
                // console.log(y);
                //console.log(y.innerHTML);
                console.log($(y).html())
            })
        }
    });


    $('p').GetText()

</script>
</body>
</html>

结果为:

jquery 便利 td jquery raty_css_56