jQuery

一 jQuery是什么? 

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

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

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

               (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)。

          <4>jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documentsevents、实现

                 动画效果,并且方便地为网站提供AJAX交互。

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

 

jQuery的引入方式:

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

二 什么是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()

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

3.1   选择器

3.1.1 基本选择器      

1
$("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")

3.1.2 层级选择器      

1
$(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")

3.1.3 基本筛选器      

1
$("li:first")第一个  $("li:last")最后一个  $("li:eq(2)") 后面数字是几就是几  $("li:even") 偶数  $("li:even") 奇数  $("li:gt(1)") 大于   $("li:lt(1)") 小于 

3.1.4 属性选择器    

1
$('[id="div1"]')   $('["alex="sb"][id]')

3.1.5 表单选择器     

1
$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")

选择器示例用法:

<!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>
<div class="outer2">Yuan</div>
<p>xialv</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.1.1.js"></script>
<script>
    //基本选择器
    $("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:eq(0)").css("color","red")
    $("li:gt(2)").css("color","red")
    $("li:lt(2)").css("color","red")

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

    //表单选择器
     //$("[type='text']").css("width","200px")
     $(":text").css("width","600px")

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

筛选器推荐用法

  <!DOCTYPE html>

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


<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>
<div class="outer2">Yuan</div>
<p>xialv</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.1.1.js"></script>  //引入jquery
<script>
    //筛选器

  //方法一:
  //$("li:eq(0)").css("color","red")

  //方法二:(推荐用法)
//$("li").eq(2).css("color","red"); //$("li").first().css("color","red"); //$("li").last().css("color","red"); </script> </body> </html>

查找筛选器用法示例:

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


<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>
<div class="outer2">Yuan</div>
<p>xialv</p>

<ul>
    <li class="begin">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.1.1.js"></script>
<script>
    //筛选器
    //$("li").eq(2).css("color","red");   //ep后面数字是几,就找到那个
    //$("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");       //向下找,找eq(2)的下一个
    //$("li").eq(2).nextAll().css("color","red");    //找所有
    //$("li").eq(2).nextUntil("#end").css("color","red");  //从那个开始,一直找到某(end)结束,但不包括自己

    //$("li").eq(4).prev().css("color","red");      //向上找,但只找一个
    //$("li").eq(4).prevAll().css("color","red");   //找他上面所有的
    //$("li").eq(4).prevUntil("li:eq(0)").css("color","red");  //从那个开始,一直找到某(end)结束,但不包括自己

    //console.log($(".outer .inner p").parent().html())   //找到他父亲
   //$(".outer .inner p").parents().css("color","red");   //一直向外找(但会继承我的属性)
   //$(".outer .inner p").parentsUntil("body").css("color","red");  //从那个开始,一直找到某(end)结束,但不包括自己 

    $(".outer").siblings().css("color","red")   //上下都找一级,自己除外

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

实例之左侧菜单 (上课讲实例)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .outer{
            height: 1000px;
             100%;
        }
        .menu{
            float: left;
            background-color: beige;
             30%;
            height: 500px;
        }
        .content{
            float: left;
            background-color: rebeccapurple;
             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.1.1.js"></script>
<script>
    function show(self) {
        $(self).next().removeClass("hide");
        $(self).parent().siblings().children(".con").addClass("hide");
    }
</script>
</body>
</html>

 运行结果:

实例之tab切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script>
           function tab(self){
               var index=$(self).attr("xxx");
               $("#"+index).removeClass("hide").siblings().addClass("hide");
               $(self).addClass("current").siblings().removeClass("current");

           }
    </script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
             60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="tab(this);">菜单一</li>
              <li xxx="c2" onclick="tab(this);">菜单二</li>
              <li xxx="c3" onclick="tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>

      </div>
</body>
</html>

3.2 筛选器

 3.2.1  过滤筛选器     

1
$("li").eq(2)  $("li").first()  $("ul li").hasclass("test")

 示例:hasClass :判断有没有这个标签名字

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

<script src="jquery-3.1.1.js"></script>
<script>
    console.log($("div").hasClass("div11"))  //判断有没有div
</script>
</body>
</html>

3.2.2  查找筛选器

$("div").children(".test")     $("div").find(".test")  
                               
 $(".test").next()    $(".test").nextAll()    $(".test").nextUntil() 
                           
 $("div").prev()  $("div").prevAll()  $("div").prevUntil()   
                        
 $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 

 $("div").siblings()

查找筛选器用法示例

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


<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>
<div class="outer2">Yuan</div>
<p>xialv</p>

<ul>
    <li class="begin">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.1.1.js"></script>
<script>
    //筛选器
    //$("li").eq(2).css("color","red");    //eq后面是几,就找第几个
    //$("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");  //从那个开始,一直找到(end)结束,不包括自己

    //$("li").eq(4).prev().css("color","red");                 //向上找一个
    //$("li").eq(4).prevAll().css("color","red");              //向上找他所有的
    //$("li").eq(4).prevUntil("li:eq(0)").css("color","red");  //从那个开始,一直找到(end)结束,不包括自己

    //console.log($(".outer .inner p").parent().html())   //找到他父亲
   //$(".outer .inner p").parents().css("color","red");   //一直向外找(继承我的属性)
   //$(".outer .inner p").parentsUntil("body").css("color","red");  //从那个开始,一直找到(end)结束,不包括自己

    $(".outer").siblings().css("color","red")  //上面都找一级,自己除外

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

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

4.1 属性操作

--------------------------属性
$("").attr();   //非固有属性,可以设置值
$("").removeAttr();
$("").prop();   //固有属性,拿属性,有两个值true和false
$("").removeProp();.
--------------------------CSS类
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------HTML代码/文本/值
$("").html([val|fn])   //取html,可以设置值
$("").text([val|fn])   //取文本
$("").val([val|fn|arr]) //查看赋的值,也也可赋值

有标签就用html,如果纯文本就用text。
--------------------------- $("").css("color","red") //设置样式

示例:

<!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.1.1.js"></script>
<script>
    console.log($("div").hasClass("div11"));
    console.log($("div").attr("con"))
    console.log($("div").attr("con","c2"))

    console.log($(":checkbox:first").attr("checked"))
    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"))

    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())
    $(":text").val("789");

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


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

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.1.1.js"></script>

<script>
    arr=[11,22,33];
//Javascripts循环用法
//    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).html("hello")
    })

</script>



</body>
</html>

注意:

attr和prop

<input id="chk1" type="checkbox" />是否可见
<input id="chk2" type="checkbox" checked="checked" />是否可见



<script>

//对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
//对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
//像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此
//需要使用prop方法去操作才能获得正确的结果。


//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    false

//  ---------手动选中的时候attr()获得到没有意义的undefined-----------
//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    true

    console.log($("#chk1").prop("checked"));//false
    console.log($("#chk2").prop("checked"));//true
    console.log($("#chk1").attr("checked"));//undefined
    console.log($("#chk2").attr("checked"));//checked
</script>

实例之全反选

<!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>
<hr>
     <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.1.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>

运行结果:

实例之模态对话框

<!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;
             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-2.1.4.min.js"></script>
<script>

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

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

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

4.2 文档处理

内部插入

    $("").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]])

文档处理的使用方法:

<!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.1.1.js"></script>
<script>
        $("button").click(function () {
           //$(".c1").append("<h1>HELLO YUAN</h1>")

            var $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)      //在标签下面插入
            //$ele.insertAfter(".c1")   //在标签下面插入(父在前,儿子在后)
            //$(".c1").before($ele)     //在标签上面插入
            //$ele.insertBefore(".c1")  
//替换 //$("p").replaceWith($ele) //找到标签p,再替换成ele
//删除与清空 //$(".c1").empty() //只清空内容,不会清空标签 //$(".c1").remove() //会把标签和内容一起清空掉 //clone (克隆:就是再复制一份) // var $ele2= $(".c1").clone(); // $(".c1").after($ele2) }) </script> </body> </html>

模态对话框(上课讲示例)

示例:

<!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;
             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.1.1.js"></script>
<script>
    function action2(self) {
        
        //实现方法一:
        $(self).parent().addClass("hide").prev().addClass("hide");

        //实现方法二//$(self).parent().prev().addClass("hide")
        //$(self).parent().parent().children(".models,.shade").addClass("hide")

    }

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

    }
//    function action2(self){
//        $(self).parent().parent().children(".models,.shade").addClass("hide")
//
//    }
</script>
</body>
</html>

运行结果:

实例之复制样式条

示例1:(上课示例,主要练习 clone使用方法)

<!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.1.1.js"></script>
<script>

    function add(self) {

        //var $clone_obj=$(".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>

运行结果:

示例2:

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

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

<script src="jquery-2.1.4.min.js"></script>
    <script>

            function add(self){
                // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
                 var $clone_obj=$(self).parent().clone();
                 $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
                 $(self).parent().parent().append($clone_obj);
            }
           function removed(self){

               $(self).parent().remove()

           }

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

4.3 css操作

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])  

备注:内容区的大小用:height,如果要包括边框的大小用:innerheight
     要包括padding就用outerHeight,要包括margin,就用outherHeight(true)参数

css操作用法示例:

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

    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div1,.div2{
             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.1.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);

   // position():相对于已经定位的父标签的偏移量

     console.log($(".div1").position().top);
     console.log($(".div1").position().left);

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


     console.log($(".div1").height("300px")); //height可以加值,也可以加参数(true)
     console.log($(".div1").innerHeight());
     console.log($(".div1").outerHeight());
     console.log($(".div1").outerHeight(true));


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

返回顶部示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div1,.div2{
             100%;
            height: 800px;
        }
        .div1{

            background-color: antiquewhite;
        }
        .div2{
            background-color: rebeccapurple;
        }

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

         .hide{
             display: none;
         }

    </style>
</head>
<body>


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

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

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

<script src="jquery-3.1.1.js"></script>
<script>
    window.onscroll=function () {
//        console.log($(window).scrollTop());

        if($(window).scrollTop()>300){
            $(".returnTop").removeClass("hide")
        }else {
            $(".returnTop").addClass("hide")
        }


    }
    function returnTop() {
        $(window).scrollTop(0)
    }


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

运行结果:

 

示例2:在页面里面加滚动滑轮

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

         .returnTop{
             position: fixed;
             right: 20px;
             bottom: 20px;
              90px;
             height: 50px;
             background-color: gray;
             color: white;
             text-align: center;
             line-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 onclick="returnTop()">return</button>
</div>

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

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


    window.onscroll=function () {


//        console.log($(window).scrollTop());

        if($(window).scrollTop()>300){
            $(".returnTop").removeClass("hide")
        }else {
            $(".returnTop").addClass("hide")
        }


    };

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



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

运行结果:

五 事件

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

事件处理
    $("").on(eve,[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)

示例2:在页面里面加滚动滑轮(绑定事件)

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

         .returnTop{
             position: fixed;
             right: 20px;
             bottom: 20px;
              90px;
             height: 50px;
             background-color: gray;
             color: white;
             text-align: center;
             line-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 onclick="returnTop()">return</button>
</div>

//绑定事件 <div class="returnTop hide" onclick="returnTop()">返回顶部</div> <script src="jquery-3.1.1.js"></script> <script> window.onscroll=function () { // console.log($(window).scrollTop()); if($(window).scrollTop()>300){ $(".returnTop").removeClass("hide") }else { $(".returnTop").addClass("hide") } }; function returnTop() { $(window).scrollTop(0) } $(".div2 button").click(function () { $(".div1").scrollTop(0) }) </script> </body> </html>

运行结果:

示例:on事件委托

<!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.1.1.js"></script>
<script>

//    var eles=document.getElementsByTagName("li")
//    eles.onclick=function () {
//        alert(123)
//    }

//    $("ul li").click(function () {
//        alert(6666)
//    });

//    $("ul li").bind("click",function () {
//        alert(777)
//    });

    //on 事件委托
    $('ul').on("click","li",function () {
       alert(999);
    });

    $("button").click(function () {

            var $ele=$("<li>");
            var len=$("ul li").length;
            $ele.html((len+1)*1111);
            $("ul").append($ele)
    });
   // $("ul li").unbind("click")

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

执行结果:

示例:ready页面加载完之后准备事件 (有问题,回去整理)

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

<script src="jquery-3.1.1.js"></script>
<script>
//    $(document).ready(function () {
//         $("ul li").html(5);
//    });

     $(function () {
        $("ul li").html(5);
     });

//    var eles=document.getElementsByTagName("li")
//    eles.onclick=function () {
//        alert(123)
//    }

//    $("ul li").click(function () {
//        alert(6666)
//    });

//    $("ul li").bind("click",function () {
//        alert(777)
//    });

    //事件委托
//    $('ul').on("click","li",function () {
//       alert(999);
//    });
//
//    $("button").click(function () {
//
//            var $ele=$("<li>");
//            var len=$("ul li").length;
//            $ele.html((len+1)*1111);
//            $("ul").append($ele)
//    });
   // $("ul li").unbind("click")

</script>
</head>
<body>

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

<button>add</button>

</body>
</html>

实例之面板拖动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.1.1.js"></script>
    <title>Title</title>
       <style>

           *{
               margin: 0;
               padding: 0;
           }
        .box{
             500px;
            height: 200px;
            position: absolute;
        }

        .title{
            background-color: black;
            height: 50px;
             500px;
            line-height: 50px;
            text-align: center;
            color: white;
        }
        .content{
             500px;
            height: 150px;
            background-color: antiquewhite;
        }
    </style>


    <script>
        $(function () {

          $(".title").mouseover(function () {
              $(this).css("cursor","pointer");
        }).mousedown(function (e) {

                  var eve = e || window.event;
                // 原始鼠标横纵坐标位置

                  var old_m_x=eve.clientX;
                  var old_m_y=eve.clientY;
//                  console.log(old_x);
//                  console.log(old_y);

                 var old_box_y=$(this).parent().offset().top ;
                 var old_box_x=$(this).parent().offset().left ;

                  $(this).bind("mousemove",function (eve) {
                      var new_m_x=eve.clientX;
                      var new_m_y=eve.clientY;

                      var m_x=new_m_x-old_m_x;
                      var m_y=new_m_y-old_m_y;



                  //$(".box").css({"top":old_box_y+m_y+"px","left":old_box_x+m_x+"px"})

                var x = old_box_x + m_x;
                var y = old_box_y + m_y;

                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');
                  })
              })
          }).mouseout(function(){
            $(this).unbind('mousemove');
        })

    </script>
</head>
<body>


<div class="box">
    <div class="title">标题</div>
    <div class="content">内容</div>
</div>

</body>
</html>

运行结果:

 

实例之放大镜

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

        }

        .outer .big_box{
            height: 400px;
             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-2.1.4.min.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>

六 动画效果

显示隐藏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.1.1.js"></script>
    <title>Title</title>
</head>
<body>
<div>hello</div>

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

    function f1() {
      $("div").show(1000)
    }

  function f2() {
      $("div").hide(1000)
    }

     function f3() {
      $("div").toggle(1000)
    }
</script>

</body>
</html>

运行结果:

滑动滑出

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.1.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">hello world</div>

</body>
</html>

运行结果:

淡入淡出

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


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

   });

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


   });
    $("#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=" 80px;height: 80px;background-color: blueviolet"></div>

</body>
</html>

运行结果:

回调函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.1.1.js"></script>
    <title>Title</title>
</head>
<body>
<div>hello</div>

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

    function f1() {
      $("div").show(1000,function () {
          alert("show")
      })
    }

//动画交果完成后,触发回调函数
  function f2() {
      $("div").hide(1000,function () {
          alert(1243)
      })
    }

     function f3() {
      $("div").toggle(1000)
    }
</script>

</body>
</html>

执行结果:

七 扩展方法 (插件机制)

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

<script>
    
$.extend(object)      //为JQuery 添加一个静态方法。
$.fn.extend(object)   //为JQuery 实例添加一个方法。


    jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
        });
    console.log($.min(3,4));

//-----------------------------------------------------------------------
    $.fn.extend({
        "print":function(){
            console.log($(this).html())
        }
    });

    $("p").print();
    
</script>

使用方法示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.1.1.js"></script>
    <title>Title</title>
</head>
<body>

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

<script>


//    $.each(obj,function () {
//
//    });

//    $("").each(function () {
//
//    })


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

//    $.Myprint();
     
//四种实现方法 $.fn.extend({ GetText:function () {
//方法一:
// for(var i=0;i<this.length;i++){ // console.log(this[i].innerHTML) // } $.each($(this),function (x,y) {
//方法二:
//console.log(y.innerHTML)

        //方法三
//console.log($(y).html()) }) } }); $("p").GetText() </script> </body> </html>

二 定义作用域

      定义一个JQuery插件,首先要把这个插件的代码放在一个不受外界干扰的地方。如果用专业些的话来说就是要为这个插件定义私有作用域。外部的代码不能直接访问插件内部的代码。插件内部的代码不污染全局变量。在一定的作用上解耦了插件与运行环境的依赖。

(function(a,b){return a+b})(3,5)

       (function ($) { })(jQuery);
//相当于
        var fn = function ($) { };
        fn(jQuery);

 三 默认参数

定义了jQuery插件之后,如果希望某些参数具有默认值,那么可以以这种方式来指定。

/step01 定义JQuery的作用域
(function ($) {
    //step03-a 插件的默认值属性
    var defaults = {
        prevId: 'prevBtn',
        prevText: 'Previous',
        nextId: 'nextBtn',
        nextText: 'Next'
        //……
    };
    //step06-a 在插件里定义方法
    var showLink = function (obj) {
        $(obj).append(function () { return "(" + $(obj).attr("href") + ")" });
    }

    //step02 插件的扩展方法名称
    $.fn.easySlider = function (options) {
        //step03-b 合并用户自定义属性,默认属性
        var options = $.extend(defaults, options);
        //step4 支持JQuery选择器
        //step5 支持链式调用
        return this.each(function () {
            //step06-b 在插件里定义方法
            showLink(this);
        });
    }
})(jQuery);

八 经典实例练习

实例之注册验证

<form class="Form">

    <p><input class="v1" type="text" name="username" mark="用户名"></p>
    <p><input class="v1" type="text" name="email" mark="邮箱"></p>
    <p><input class="v1" type="submit" value="submit"  onclick="return validate()"></p>

</form>

<script src="jquery-3.1.1.js"></script>
<script>
    // 注意:
    // DOM对象--->jquery对象    $(DOM)
    // jquery对象--->DOM对象    $("")[0]

    //---------------------------------------------------------


    // DOM绑定版本
    function validate(){

        flag=true;

        $("Form .v1").each(function(){
            $(this).next("span").remove();// 防止对此点击按钮产生多个span标签
              var value=$(this).val();
            if (value.trim().length==0){
                 var mark=$(this).attr("mark");
                 var ele=document.createElement("span");
                 ele.innerHTML=mark+"不能为空!";
                 $(this).after(ele);
                 $(ele).prop("class","error");// DOM对象转换为jquery对象
                 flag=false;
                 //  return false-------->引出$.each的return false注意点
            }


        });

        return flag
    }
                   //---------------------------------------------------------
//---------------------------------------------------------
                   //---------------------------------------------------------



        function f(){

        for(var i=0;i<4;i++){

            if (i==2){
                return
            }
            console.log(i)
        }

    }
    f();  // 这个例子大家应该不会有问题吧!!!
//------------------------------------------
    li=[11,22,33,44];
    $.each(li,function(i,v){

        if (v==33){
                return ;   //  ===试一试 return false会怎样?
            }
            console.log(v)
    });

//------------------------------------------

    //  $.MyEach(obj,function(i,v){}):
         for(var i in obj){

             func(i,obj[i]) ; //  i就是索引,v就是对应值
             // {}:我们写的大括号的内容就是func的执行语句;
         }

    // 大家再考虑: function里的return只是结束了当前的函数,并不会影响后面函数的执行

    //本来这样没问题,但因为我们的需求里有很多这样的情况:我们不管循环到第几个函数时,一旦return了,
    //希望后面的函数也不再执行了!基于此,jquery在$.each里又加了一步:
         for(var i in obj){

             ret=func(i,obj[i]) ;
             if(ret==false){
                 return ;
             }

         }
    // 这样就很灵活了:
    // <1>如果你想return后下面循环函数继续执行,那么就直接写return或return true
    // <2>如果你不想return后下面循环函数继续执行,那么就直接写return false


// ---------------------------------------------------------------------
   // 说了这么多,请问大家如果我们的需求是:判断出一个输入有问题后面就不判断了(当然也就不显示了),
   // 怎么办呢?
   // 对了
    if (value.trim().length==0){
                  //...
                  //...
                  //flag=false;  //   flag=false不要去,它的功能是最后如果有问题,不提交数据!
                  return false
            }


//最后,大家尝试着用jquery的绑定来完成这个功能!

      $(".Form :submit").click(function(){});
    
</script>

参考:http://www.cnblogs.com/xcj26/p/3345556.html

参考:http://jquery.cuishifeng.cn/index.html

原文地址:https://www.cnblogs.com/nulige/p/6405791.html