• jQuery至上宝典


    一 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 对象, 那么要在变量前面加上$. 书写时$等同于jquery
    
    var $variable = jQuery 对象
    var variable = DOM 对象
    
    $variable[0]:jquery对象转为dom对象      $("#msg").html(); $("#msg")[0].innerHTML

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

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

    3.1   选择器

    3.1.1 基本选择器      

    $("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")
    分别是所有、id、class、元素、多个元素查找的选择器
    

    3.1.2 层级选择器      

    $(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")
    分别是后代选择器 子代选择器 毗邻选择器 普通兄弟选择器
    

    3.1.3 基本筛选器      

    $("li:first") $("li:last")  $("li:eq(2)")  $("li:even")  $("li:odd") $("li:gt(1)")  $("li:lt(1)") 
    
    分别是第一个、最后一个、索引第三个、取奇数、取偶数、指定大于索引得值、指定小于索引得值
    

    3.1.4 属性选择器    

    $('["alex"]') $('[id="div1"]')   $('["alex="sb"][id]')
    模糊查找属性,精确查找属性
    

    3.1.5 表单选择器     

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

    实例之左侧菜单

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>left_menu</title>
    
        <style>
              .menu{
                  height: 500px;
                  width: 30%;
                  background-color: gainsboro;
                  float: left;
              }
              .content{
                  height: 500px;
                  width: 70%;
                  background-color: rebeccapurple;
                  float: left;
              }
             .title{
                 line-height: 50px;
                 background-color: #425a66;
                 color: forestgreen;}
    
    
             .hide{
                 display: none;
             }
    
    
        </style>
    </head>
    <body>
    
    <div class="outer">
        <div class="menu">
            <div class="item">
                <div class="title">菜单一</div>
                <div class="con">
                    <div>111</div>
                    <div>111</div>
                    <div>111</div>
                </div>
            </div>
            <div class="item">
                <div class="title">菜单二</div>
                <div class="con hide">
                    <div>111</div>
                    <div>111</div>
                    <div>111</div>
                </div>
            </div>
            <div class="item">
                <div class="title">菜单三</div>
                <div class="con hide">
                    <div>111</div>
                    <div>111</div>
                    <div>111</div>
                </div>
            </div>
    
        </div>
        <div class="content"></div>
    
    </div>
    <script src="jquery-3.2.1.js"></script>
    <script>
               $(".item .title").click(function () {
                    $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");
    
    //                $(this).next().removeClass("hide");
    //                $(this).parent().siblings().children(".con").addClass("hide");
               })
    </script>
    
    
    </body>
    </html>
    View Code

    实例之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;
                width: 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>
    View Code

    3.2 筛选器

     3.2.1  过滤筛选器     

    $("li").eq(2)  $("li").first()  $("ul li").hasclass("test")
    这种eq取值得方式,比$("li:eq(2)")这种好
    

     3.2.2  查找筛选器

     孩子组 
     $("div").children(".test")     $("div").find(".test")  分别是儿子代和后代
    
     兄弟标签 next nextAll nextUntil 往下找     
     $(".test").next()    $(".test").nextAll()    $(".test").nextUntil()  分别是下一个标签、下面所有标签、区间
    
     兄弟标签 prov provAll provUntill 往上找                  
     $("div").prev()  $("div").prevAll()  $("div").prevUntil() 同上相反   
    
     父亲标签                  
     $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 同上
    
     查找所有兄弟标签,重点
     $("div").siblings()
    

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

    4.1 属性操作

    --------------------------属性
    $("").attr();
    $("").removeAttr();
    $("").prop();
    $("").removeProp();
    --------------------------CSS类
    $("").addClass(class|fn)
    $("").removeClass([class|fn])
    --------------------------HTML代码/文本/值
    $("").html([val|fn])
    $("").text([val|fn])
    $("").val([val|fn|arr])
    ---------------------------
    $("").css("color","red")

    注意:

    对于属性操作: attr:操作自定义属性  prop:操作固有属性
      prop("属性名") -------取值
      prop("属性名",属性值) -------赋值
           var()针对的是固有属性的value值
    <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>
    
    attr和prop
    View Code

    实例之全反选

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-1.11.3.min.js"></script>
        <script>
    
                 function selectall(){
    
                     $("table :checkbox").prop("checked",true)
                 }
                 function cancel(){
    
                     $("table :checkbox").prop("checked",false)
                 }
    
                 function reverse(){
    
    
                     //                 var idlist=$("table :checkbox")
    //                 for(var i=0;i<idlist.length;i++){
    //                     var element=idlist[i];
    //
    //                     var ischecked=$(element).prop("checked")
    //                     if (ischecked){
    //                         $(element).prop("checked",false)
    //                     }
    //                     else {
    //                         $(element).prop("checked",true)
    //                     }
    //
    //                 }
    //    jquery循环的两种方式
                     //方式一
    //                 li=[10,20,30,40]
    //                 dic={name:"yuan",sex:"male"}
    //                 $.each(li,function(i,x){
    //                     console.log(i,x)
    //                 })
    
                     //方式二
    //                    $("tr").each(function(){
    //                        console.log($(this).html())
    //                    })
    
    
    
                     $("table :checkbox").each(function(){
    
                         $(this).prop("checked",!$(this).prop("checked"));
    
    //                     if ($(this).prop("checked")){
    //                         $(this).prop("checked",false)
    //                     }
    //                     else {
    //                         $(this).prop("checked",true)
    //                     }
    
                         // 思考:如果用attr方法可以实现吗?
    
    
                     });
                 }
    
        </script>
    </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>
    
    
    
    </body>
    </html>
    View Code

    实例之模态对话框

    <!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-1.11.3.min.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").prev().addClass("hide")
    
        }
    </script>
    </body>
    </html>
    View Code

    4.2 文档处理

    //创建一个标签对象
        $("<p>")
    
    
    //内部插入
    
        $("").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]])
    //内部插入
    //$("div").append("<h1>yuan</h1>") //后面插入
    //$("div").prepend("<h1>yuan</h1>") //前面插入
    //$("div").prepend("<p>egon</p>") //插入到最上面
    
    //var $ele=$("<p>yuan</p>")
    //$ele.appendTo("div") //子节点插入父节点,上面是父节点插入子节点
    
    //外部插入
    //$("div").after("<h1>egon</h1>") //在之后插入兄弟标签
    //$("div").before("<h1>egon</h1>") //在之前插入兄弟标签
    
    //替换
    //$("div").replaceWith("<h1>egon</h1>") //替换
    
    //删除
    //$("div").empty() //清空内容,标签还在
    //$("div").remove() //清空内容,标签也被清空
    
    //复制
    //var $ele=$("div").clone()
    //$("body").append($ele)  //克隆应用
    文档处理补充

    实例之复制样式条

    <!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-1.11.3.min.js"></script>
        <script>
                //var $clone_obj=$(self).parent().clone();  // $clone_obj放在这个位置可以吗?
                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>
    View Code

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

    偏移量:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                /*margin: 0;*/   /*如果加它,p1左边的偏移量是8*/
            }
        </style>
    </head>
    <body>
    
    <h1>偏移量介绍</h1>
    <p class="p1">first para</p>
    <p class="p2">second para</p>
    
    <button>offset</button>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
        var $p_offset=$(".p1").offset() //p1的偏移量对象
        var $left=$p_offset.left;
        var $top=$p_offset.top;
    
        $(".p2").text(" the left: "+$left+" the top: "+$top); //显示p1的左偏移和上偏移量
    
        $("button").click(function () {
            $(".p1").offset({left:100,top:200}) //距离左一百,上两百
        })
    
    
    </script>
    </body>
    </html>
    offset
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
            }
            .t1{
                width: 200px;
                height: 200px;
                background-color: wheat;
            }
            .box1{
                width:200px;
                height:200px;
                background-color: darkgreen;
                /*position: relative;  如果父基不加定位,默认按body定位*/
            }
    
            .box2{
                width:100px;
                height:100px;
                background-color: palevioletred;
            }
        </style>
    </head>
    <body>
    
    <div class="t1"></div>
    <div class="box1">
        <div class="box2"></div>
    </div>
    <p class="p2"></p>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
    
        var $p_position=$(".box2").position() //p1的position偏移量对象
        var $left=$p_position.left;
        var $top=$p_position.top;
    
        $(".p2").text(" the left: "+$left+" the top: "+$top); //显示p1的左偏移和上偏移量
    
    
    
    </script>
    </body>
    </html>
    position

    实例返回顶部

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
                padding:0;
            }
            .back{
                background-color: wheat;
            }
            .top{
                background-color: royalblue;
                height: 40px;
                width: 80px;
                color: white;
                position: fixed;
                right: 20px;
                bottom: 20px;
            }
    
        </style>
    </head>
    <body>
    <div class="back">
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
        <h1>1111</h1>
    </div>
    
    <div class="top">返回顶部</div>
    <script src="jquery-3.2.1.js"></script>
    <script>
        $(".top").click(function () {
            $(window).scrollTop(0)  //为什么不能用.back,因为top针对得是整个窗口,所以用window
        })
    
        window.onscroll=function () {   //必须用到window.onscroll
            //console.log($(window).scrollTop())
            if ($(window).scrollTop()>200){
            $(".top").show()
            }else {
                $(".top").hide()
            }
        }
    
    </script>
    </body>
    </html>
    View Code

     尺寸:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            .d1{
                width: 200px;
                height: 200px;
                background-color: wheat;
                padding: 50px;
                margin: 50px;
                border:10px solid black;
            }
    
        </style>
    </head>
    <body>
    
    <div class="d1">DIVDIVDIVDIVDIVDIVDIV</div>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
    
        //$(".d1").height("400px"); //默认不加参数是取值操作,加参数是赋值操作
        console.log($(".d1").height()); //200px
        console.log($(".d1").innerHeight()); //300px
        console.log($(".d1").outerHeight()); //320px
        console.log($(".d1").outerHeight(true)); //420px
    </script>
    
    </body>
    </html>
    
    <!--$("").height([val|fn]) 内容区域的高度-->
    <!--$("").width([val|fn]) 内容区域的宽度-->
    <!--$("").innerHeight() 内容+padding区域的高度-->
    <!--$("").innerWidth() 内容+padding区域的宽度-->
    <!--$("").outerHeight([soptions]) 内容+padding+border+margin区域的高度 -->
    <!--需要加上true,outerHeight(ture),默认是false,不加true只能取到border。-->
    
    <!--$("").outerWidth([options]) 内容+padding+border+margin区域的宽度-->
    View Code

     4.4 事件

    页面载入

    ready(fn)  // 当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
    $(document).ready(function(){}) -----------> 简写形式 $(function(){})  
    
    ready是对window.onload方法的替代方法
    windows.onload=function(){}

    事件绑定

    //语法:  标签对象.事件(函数) ,直接绑定形式
     $("p").click(function(){})

    事件委派

    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-3.2.1.js"></script>
        <script>
        //$("button").click(function () {
        //    $("ul").append("<li>222</li>")
        //});
    
        //$("li").click(function () {
        //    alert(123)  //新添加222没有绑定
        //})
    
        //$("p").bind("click",function () { //jQuery2版本中用
        //    alert(456)
        //});
    
        //windows.onload=function(){}
    
        $(function () {  // $(document).ready(function (){}的简写形式
            $("p").css("color","red")
        });
    
        $(document).ready(function () {  // ready 页面载入,是对window.load的替代方法
            $("p").on("click",function () { //jQuery3版本中用
            alert(999)
        });
            $(".off_p").click(function () { //取消所有绑定事件
            $("p").off()
        });
        });
    
    
        //事件委派方式,所以add 222 也有绑定
        //$("ul").on("click","li",function () {
        //    alert(100)
        //})
    
    
    </script>
    </head>
    <body>
    <p>PPPP</p>
    
    <ul>
        <li>111</li>
        <li>111</li>
        <li>111</li>
        <li>111</li>
        <li>111</li>
        <li>111</li>
    </ul>
    
    <button>add</button>
    <button class="off_p">off</button>
    
    </body>
    </html>
    事件委派

    事件切换

    hover事件:

    一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。

    over:鼠标移到元素上要触发的函数

    out:鼠标移出元素要触发的函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            .test{
                 200px;
                height: 200px;
                background-color: wheat;
            }
        </style>
    </head>
    <body>
    
    
    <div class="test"></div>
    </body>
    <script src="jquery-3.2.1.js"></script>
    <script>
    //    function enter(){
    //        console.log("enter")
    //    }
    //    function out(){
    //        console.log("out")
    //    }
    // $(".test").hover(enter,out)
    
    $(".test").mouseenter(function(){
            console.log("enter")
    });
    
    $(".test").mouseleave(function(){
            console.log("leave")
        });
    </script>
    </html>
    事件切换

    4.5 each循环

    我们知道,

    $("p").css("color","red")  
    

    是将css操作加到所有的标签上,内部维持一个循环;但如果对于选中标签进行不同处理,这时就需要对所有标签数组进行循环遍历啦

    jquery支持两种循环方式:

    方式一:

    格式:$.each(obj,fn)

    $.each([111,222,333],function(i,j){
         console.log(i)   // i : 索引
         console.log(j)   // j : 元素值
    })
    
    $.each({"name":"alex"},function(i,j){
         console.log(i)   // i : key
         console.log(j)   // j : value
    })

     方式二:

    格式:$("").each(fn)

    $("tr").each(function(){
        console.log($(this).html())
    })

    其中,$(this)代指当前循环标签。

    each扩展

    /*
            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)
        });
    
    //------------------------------------------
    
    
        // 大家再考虑: 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
    
    
    // ---------------------------------------------------------------------

    4.6 动画效果

    显示隐藏

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <p>hello world</p>
    <img src="http://www.xiaohuar.com/d/file/20170619/e0456729d4dcbea569a1acbc6a47ab69.jpg" height="200px" width="200px" alt="">
    <button id="show">显示</button>
    <button id="hide">隐藏</button>
    <button id="toggle">toggle</button>
    
    </body>
    <script src="jquery-3.2.1.js"></script>
    <script>
            //  标签对象.事件(function(){})
            //        $("#show").click(function () {
            //            alert(123)
            //        })
    
            $("#show").click(function () {
                $("P").show(1000,function () {
                    alert("hide complete")
                })
            })
            $("#hide").click(function () {
                $("P").hide(1000,function () {
                    alert("show complete!")
                })
            })
            $("#toggle").click(function () {
                $("p").toggle(1000)
            })
    
            //回调函数:当某一个动作执行完成之后自动触发的函数
    //        $("#show").click(function () {
    //            $("img").show(1000)
    //        })
    //        $("#hide").click(function () {
    //            $("img").hide(1000)
    //        })
    //        $("#toggle").click(function () {
    //            $("img").toggle(1000)
    //        })
    
    </script>
    </html>
    View Code

    滑动

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            #con{
                line-height:80px;
                background-color: darkblue;
                color: white;
                text-align: center;
            }
        </style>
    </head>
    <body>
    
    <button id="slideDown">slideDown</button>
    <button id="slideUp">slideUp</button>
    <button id="toggle">toggle</button>
    
    <div id="con">滑动效果</div>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
        $("#slideDown").click(function () {
            $("#con").slideDown()
        });
    
        $("#slideUp").click(function () {
            $("#con").slideUp()
        });
        $("#toggle").click(function () {
            $("#con").toggle()
        });
    </script>
    </body>
    </html>
    View Code

    淡入淡出

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .con{
                400px;
                height: 400px;
                background-color: darksalmon;
            }
        </style>
    </head>
    <body>
    
    <div class="con"></div>
    <hr>
    <button id="fadeIn">fadeIn</button>
    <button id="fadeOut">fadeOut</button>
    <button id="fadeToggle">fadeToggle</button>
    <button id="fadeTo">fadeToggle</button>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
        $("#fadeIn").click(function () {
            $(".con").fadeIn(2000);
        })
        $("#fadeOut").click(function () {
            $(".con").fadeOut(2000);
        })
        $("#fadeToggle").click(function () {
            $(".con").fadeToggle(2000);
        })
        $("#fadeTo").click(function () {
            $(".con").fadeTo(2000,0.4); //透明度
        })
    
    
        //淡入淡出:隐藏与显示有了一个透明度渐变的效果 应用:替换removeClass("hide") addClass("hide")
    
    </script>
    
    </body>
    </html>
    View Code

    回调函数

    回调函数:当某一个动作执行完成之后自动触发的函数
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-2.1.4.min.js"></script>
    
    </head>
    <body>
      <button>hide</button>
      <p>helloworld helloworld helloworld</p>
    
    
    
     <script>
       $("button").click(function(){
           $("p").hide(1000,function(){
               alert($(this).html())
           })
    
       })
        </script>
    </body>
    </html>
    View Code

    五 扩展方法

    //$.ajax() //基于类的方法   $("").each() //基于对象的方法

    jQuery.extend(object)

    扩展jQuery对象本身。

    用来在jQuery命名空间上增加新函数。 

    在jQuery命名空间上增加两个函数:

    <script>
        jQuery.extend({ //像$.each都是$.extend方法扩展的
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
    });
    
    
        jQuery.min(2,3); // => 2 最小值
        jQuery.max(4,5); // => 5 最大值
    </script>

    jQuery.fn.extend(object)

    扩展 jQuery 元素集来提供新的方法(通常用来制作插件)

    增加两个插件方法:

    <body>
    
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    
    <script src="jquery.min.js"></script>
    <script>
        jQuery.fn.extend({
          check: function() {
             $(this).attr("checked",true);
          },
          uncheck: function() {
             $(this).attr("checked",false);
          }
        });
    
    
        $(":checkbox:gt(0)").check()
    </script>
    
    </body>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    
    <button>change</button>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
    
        //$.ajax() //基于类的方法   $("").each() //基于对象的方法
    
    
        $.extend({     //像$.each都是$.extend方法扩展的
            minsss:function (a,b) {
                return a < b ? a : b;
            },
            maxsss:function (a,b) {
                return a > b ? a : b;
            }
        });
    
        console.log($.minsss(3,6)); //取最小值
        console.log($.maxsss(3,6)); //取最大值
    
        $.fn.extend({
            checkall:function () {
                //console.log(this)
                this.each(function () {     // this:[input1 input]
                    this.checked=true;      // this: [当前这一个标签]
                })
            }
        });
    
        //$(":checkbox").checkall()
        $("button").click(function () {
            $(":checkbox:even").checkall()
        })
    </script>
    </body>
    </html>
    插件机制

    六 实例练习

    左侧菜单

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>left_menu</title>
    
        <style>
              .menu{
                  height: 500px;
                   20%;
                  background-color: gainsboro;
                  text-align: center;
                  float: left;
              }
              .content{
                  height: 500px;
                   80%;
                  background-color: darkgray;
                  float: left;
              }
             .title{
                 line-height: 50px;
                 background-color: wheat;
                 color: rebeccapurple;}
    
    
             .hide{
                 display: none;
             }
    
    
        </style>
    </head>
    <body>
    
    <div class="outer">
        <div class="menu">
            <div class="item">
                <div class="title">菜单一</div>
                <div class="con">
                    <div>111</div>
                    <div>111</div>
                    <div>111</div>
                </div>
            </div>
            <div class="item">
                <div class="title">菜单二</div>
                <div class="con hide">
                    <div>222</div>
                    <div>222</div>
                    <div>222</div>
                </div>
            </div>
            <div class="item">
                <div class="title">菜单三</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.min.js"></script>
    <script>
               $(".item .title").mouseover(function () {
                    $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");
    
    //                $(this).next().removeClass("hide");
    //                $(this).parent().siblings().children(".con").addClass("hide");
               })
    </script>
    
    
    </body>
    </html>
    View Code

    Tab切换

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>tab</title>
    
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            .tab_outer{
                margin: 20px auto;
                 60%;
            }
            .menu{
                background-color: #cccccc;
                /*border: 1px solid red;*/
                line-height: 40px;
                text-align: center;
            }
            .menu li{
                display: inline-block;
                margin-left: 14px;
                padding:5px 20px;
    
            }
            .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: #2868c8;
                color: white;
                border-top: solid 2px rebeccapurple;
            }
        </style>
    </head>
    <body>
          <div class="tab_outer">
              <ul class="menu">
                  <li relation="c1" class="current">菜单一</li>
                  <li relation="c2" >菜单二</li>
                  <li relation="c3">菜单三</li>
              </ul>
              <div class="content">
                  <div id="c1">内容一</div>
                  <div id="c2" class="hide">内容二</div>
                  <div id="c3" class="hide">内容三</div>
              </div>
    
          </div>
    </body>
    
    
    <script src="jquery.min.js"></script>
        <script>
              $(".menu li").click(function(){
    
                   var index=$(this).attr("relation");
                   $("#"+index).removeClass("hide").siblings().addClass("hide");
                   $(this).addClass("current").siblings().removeClass("current");
    
              });
    
    
        </script>
    </html>
    View Code

    table正反选

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
    
         <button>全选</button>
         <button>取消</button>
         <button>反选</button>
         <hr>
         <table border="1">
             <tr>
                 <td><input type="checkbox"></td>
                 <td>111</td>
                 <td>111</td>
                 <td>111</td>
                 <td>111</td>
             </tr>
             <tr>
                 <td><input type="checkbox"></td>
                 <td>222</td>
                 <td>222</td>
                 <td>222</td>
                 <td>222</td>
             </tr>
             <tr>
                 <td><input type="checkbox"></td>
                 <td>333</td>
                 <td>333</td>
                 <td>333</td>
                 <td>333</td>
             </tr>
             <tr>
                 <td><input type="checkbox"></td>
                 <td>444</td>
                 <td>444</td>
                 <td>444</td>
                 <td>444</td>
             </tr>
         </table>
    
    
    
    
    <script src="jquery.min.js"></script>
        <script>
    
                $("button").click(function(){
    
                   if($(this).text()=="全选"){    // $(this)代指当前点击标签
    
                       $("table :checkbox").prop("checked",true)
                   }
                    else if($(this).text()=="取消"){
                       $("table :checkbox").prop("checked",false)
                   }
                    else {
                       $("table :checkbox").each(function(){
    
                         $(this).prop("checked",!$(this).prop("checked"));
    
                     });
                   }
    
    
    
                });
    
        </script>
    </body>
    </html>
    View Code

    模态对话框

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
            }
            .back{
                background-color: wheat;
                height: 2000px;
            }
    
            .shade{
                position: fixed;
                top: 0;
                bottom: 0;
                left:0;
                right: 0;
                background-color: darkgray;
                opacity: 0.4;
            }
    
            .hide{
                display: none;
            }
    
            .models{
                position: fixed;
                top: 50%;
                left: 50%;
                margin-left: -100px;
                margin-top: -100px;
                height: 200px;
                 200px;
                background-color: white;
    
            }
        </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.min.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").prev().addClass("hide")
    
        }
    </script>
    </body>
    </html>
    View Code

    复制样式条

    <!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="+">
                            <input type="text">
                    </div>
                </div>
    
    
    <script src=jquery.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()
    
               }
    
    
    /*
            $("[value='+']").click(function(){
    
                 var $clone_obj=$(this).parent().clone();
                     $clone_obj.children(":button").val("-").attr("class","mark");
                     $(this).parent().parent().append($clone_obj);
    
            });
    
    
    
            $(".outer").on("click",".item .mark",function(){
    
                console.log($(this));  // $(this):  .item .mark标签
                $(this).parent().remove()
    
            })
    
    */
    
    
        </script>
    </body>
    </html>
    View Code

    注册验证

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    
    
    <form class="Form" id="form">
    
        <p><input class="v1" type="text" name="username" mark="用户名"></p>
        <p><input class="v1" type="text" name="email" mark="邮箱"></p>
        <p><input type="submit" value="submit"></p>
    
    </form>
    
    <script src="jquery.min.js"></script>
    <script>
    
    
        $("#form :submit").click(function(){
              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
        });
    
    
    
    
    </script>
    </body>
    </html>
    View Code

    拖动面板

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div style="border: 1px solid #ddd; 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.min.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).on('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).off('mousemove');
            });
        })
    </script>
    </body>
    </html>
    View Code

    轮播图

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <script src="jquery-3.1.1.js"></script>
        <title>Title</title>
    
    
        <style>
    
                .outer{
                     790px;
                    height: 340px;
                    margin: 80px auto;
                    position: relative;
                }
    
                .img li{
                     position: absolute;
                     list-style: none;
                     top: 0;
                     left: 0;
                     display: none;
                }
    
               .num{
                   position: absolute;
                   bottom: 18px;
                   left: 270px;
                   list-style: none;
    
    
               }
    
               .num li{
                   display: inline-block;
                    18px;
                   height: 18px;
                   background-color: white;
                   border-radius: 50%;
                   text-align: center;
                   line-height: 18px;
                   margin-left: 4px;
               }
    
               .btn{
                   position: absolute;
                   top:50%;
                    30px;
                   height: 60px;
                   background-color: lightgrey;
                   color: white;
    
                   text-align: center;
                   line-height: 60px;
                   font-size: 30px;
                   opacity: 0.7;
                   margin-top: -30px;
    
                   display: none;
    
               }
    
               .left{
                   left: 0;
               }
    
               .right{
                   right: 0;
               }
    
              .outer:hover .btn{
                  display: block;
              }
    
            .num .active{
                background-color: red;
            }
        </style>
    
    </head>
    <body>
    
    
          <div class="outer">
              <ul class="img">
                  <li style="display: block"><a href=""><img src="img/1.jpg" alt=""></a></li>
                  <li><a href=""><img src="img/2.jpg" alt=""></a></li>
                  <li><a href=""><img src="img/3.jpg" alt=""></a></li>
                  <li><a href=""><img src="img/4.jpg" alt=""></a></li>
                  <li><a href=""><img src="img/5.jpg" alt=""></a></li>
                  <li><a href=""><img src="img/6.jpg" alt=""></a></li>
              </ul>
    
              <ul class="num">
                  <!--<li class="active"></li>-->
                  <!--<li></li>-->
                  <!--<li></li>-->
                  <!--<li></li>-->
                  <!--<li></li>-->
                  <!--<li></li>-->
              </ul>
    
              <div class="left  btn"> < </div>
              <div class="right btn"> > </div>
    
          </div>
    <script src="jquery-3.1.1.js"></script>
    <script>
        var i=0;
    //  通过jquery自动创建按钮标签
    
        var img_num=$(".img li").length;
    
        for(var j=0;j<img_num;j++){
            $(".num").append("<li></li>")
        }
    
        $(".num li").eq(0).addClass("active");
    
    
    // 手动轮播
    
        $(".num li").mouseover(function () {
            i=$(this).index();
            $(this).addClass("active").siblings().removeClass("active");
    
            $(".img li").eq(i).stop().fadeIn(200).siblings().stop().fadeOut(200)
    
        });
    
    
    // 自动轮播
        var c=setInterval(GO_R,1500);
    
        function GO_R() {
    
            if(i==img_num-1){
                i=-1
            }
             i++;
             $(".num li").eq(i).addClass("active").siblings().removeClass("active");
             $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000)
    
        }
    
    
        function GO_L() {
            if(i==0){
                i=img_num
            }
             i--;
             $(".num li").eq(i).addClass("active").siblings().removeClass("active");
             $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);  // fadeIn,fadeOut单独另开启的线程
    
    
        }
        $(".outer").hover(function () {
            clearInterval(c)
        },function () {
            c=setInterval(GO_R,1500)
        });
    
    
    
    // button 加定播 
        $(".right").click(GO_R);
        $(".left").click(GO_L)
    
    
    
    </script>
    </body>
    </html>
    View Code
  • 相关阅读:
    Aurora 数据库支持多达五个跨区域只读副本
    Amazon RDS 的 Oracle 只读副本
    Amazon EC2 密钥对
    DynamoDB 读取请求单位和写入请求单位
    使用 EBS 优化的实例或 10 Gb 网络实例
    启动 LAMP 堆栈 Web 应用程序
    AWS 中的错误重试和指数退避 Error Retries and Exponential Backoff in AWS
    使用 Amazon S3 阻止公有访问
    路由表 Router Table
    使用MySQLAdmin工具查看QPS
  • 原文地址:https://www.cnblogs.com/luchuangao/p/6946710.html
Copyright © 2020-2023  润新知