zoukankan      html  css  js  c++  java
  • 前端基础之jQuery

    概述

    jQuery是目前使用最广泛的javascript函数库。据统计,全世界排名前100万的网站,有46%使用jQuery,远远超过其他库。微软公司甚至把jQuery作为他们的官方库。

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

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

    jQuery的版本分为1.x系列和2.x、3.x系列,1.x系列兼容低版本的浏览器,2.x、3.x系列放弃支持低版本浏览器

    jquery是一个函数库,一个js文件,页面用script标签引入这个js文件就可以使用。

    <script type="text/javascript" src="js/jquery-3.2.1.js"></script>
    

     http://jquery.com/ 官方网站

    jQuery对象

    jQuery对象就是通过jQuery包装DOM对象后产生的对象。

    jQuery对象是jQuery独有的.如果一个对象是jQuery对象那么它就可以使用jQuery里的方法。

    $("#test").html() :获取ID为test的元素内的html代码。
    等同于用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()  

     

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

    选择器

    基本选择器     

    $("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")
    //通配   ID选择器   class类选择器  标签选择器    多元素选择器

    层级选择器  

    $(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div") 
    //后代选择器        子代选择器            毗邻元素选择器    兄弟选择器
    

     基本筛选器

    $("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")  $("li:lt(4)")  $("li:odd")
    //                    偶       索引大于1   索引小于4        奇

    属性选择器

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

     表单选择器     

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

     表单属性选择器

    <body>
    
    <form>
        <input type="checkbox" value="123" checked>
        <input type="checkbox" value="456" checked>
    
    
      <select>
          <option value="1">Flowers</option>
          <option value="2" selected="selected">Gardens</option>
          <option value="3" selected="selected">Trees</option>
          <option value="3" selected="selected">Trees</option>
      </select>
    </form>
    
    
    <script src="jquery.min.js"></script>
    <script>
        // console.log($("input:checked").length);     // 2
    
        // console.log($("option:selected").length);   // 只能默认选中一个,所以只能lenth:1
    
        $("input:checked").each(function(){
    
            console.log($(this).val())
        })
    
    </script>
    
    
    </body>
    

    筛选器

    过滤筛选器   

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

     查找筛选器

     查找子标签:         $("div").children(".test") //查找子代     $("div").find(".test")  //查找所有后代
                                   
     向下查找兄弟标签:    $(".test").next()               $(".test").nextAll()     
                        $(".test").nextUntil() 
                               
     向上查找兄弟标签:    $("div").prev()                  $("div").prevAll()       
                        $("div").prevUntil()   
     查找所有兄弟标签:    $("div").siblings()  
                  
     查找父标签:         $(".test").parent()              $(".test").parents()     
                        $(".test").parentUntil() 
    

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

    事件

    页面载入

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

     事件绑定

    //语法:  标签对象.事件(函数)    
    eg: $("p").click(function(){})
    

     事件委派

    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。
    
    <body>
    <ul>
        <li>111</li>
        <li>222</li>
        <li>333</li>
    </ul>
    <button id="add_li">ADD</button>
    <button id="off">OFF</button>
    <script>
        $("ul li").click(function () {
            alert(123)
        });
        $("#add_li").click(function () {
            var $li=$("<li>");
            $li.text(Math.round(Math.random()*100));
            $("ul").append($li);
        });
        $("#off").click(function () {
            $("ul li").off();
        })
    </script>
    </body>
    
    //点击111、222、333会 alert(123),但是后添加的li标签不会绑定此事件
    //点击off会解除<li>111</li>、<li>222</li>、<li>333</li>标签与点击触发alert(123)事件的绑定
    
    <body>
    <ul>
        <li>111</li>
        <li>222</li>
        <li>333</li>
    </ul>
    <button id="add_li">ADD</button>
    <button id="off">OFF</button>
    <script>
        $("ul").on("click","li",function () {
            alert(123)
        });
        $("#add_li").click(function () {
            var $li=$("<li>");
            $li.text(Math.round(Math.random()*100));
            $("ul").append($li);
        });
        $("#off").click(function () {
            $("ul").off();
        })
    </script>
    </body>
    //为了解决上面遇到的问题,有了事件委派这种解决方法,新添加的<li>标签也可以绑定点击触发alert(123)的事件
    //父标签将事件委派给子标签,注意父标签必须是一个不动的标签
    //给谁绑定,就给谁解绑
    

     事件切换

    hover事件:

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

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

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

    <style>
        *{
            margin:0;
            padding:0;
        }
         .test{
    
                 200px;
                height: 200px;
                background-color: wheat;
    
            }
    </style>
    <body>
    <div class="test"></div>
    </body>
    <script>
        function enter() {
            console.log(123)
        }
        function out() {
            console.log(456)
        }
        $(".test").hover(enter,out)
    
    </script>
    
    <style>
        *{
            margin:0;
            padding:0;
        }
         .test{
    
                 200px;
                height: 200px;
                background-color: wheat;
    
            }
    </style>
    <body>
    <div class="test"></div>
    </body>
    <script>
    
        $(".test").mouseenter(function () {
            console.log(123)
        });
        $(".test").mouseleave(function () {
            console.log(456)
        })
    </script>
    

     属性操作

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

     attr方法使用:

    <input id="chk1" type="checkbox" />是否可见
    <input id="chk2" type="checkbox" checked="checked" />是否可见
    
    
    
    <script>
    
    //对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
    //对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
    //像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此
    //需要使用prop方法去操作才能获得正确的结果。
    
    
    //  ---------手动选中的时候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>
    

     each循环

     我们知道,

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

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

    jquery支持两种循环方式:

    方式一

    格式:$.each(obj,fn)

    <script>
        li=[11,22,33,44];
        dic={"name":"kaylee","sex":"male"};
        $.each(li,function (i,v) {
            console.log(i,v)
        })
    </script>
    运行结果:
    0 11
    1 22
    2 33
    3 44
    
    <script>
        li=[11,22,33,44];
        dic={"name":"kaylee","sex":"male"};
        $.each(dic,function (i,v) {
            console.log(i,v)
        })
    </script>
    运行结果:
    name kaylee
    sex male
    

     方式二

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

    <body>
    <ul>
        <li>111</li>
        <li>222</li>
        <li>333</li>
    </ul>
    <script>
        $("li").each(function () {
            console.log($(this).html());  // 其中,$(this)代指当前循环标签。
        })
    </script>
    </body>
    

    each扩展

    <script>
        function f() {
            for(var i=0;i<4;i++){
                if(i==2){
                    return
                }
                console.log(i)
            }
        }
        f();
    </script>
    运行结果:
    0
    1
    
    <script>
        li=[11,22,33,44];
        $.each(li,function (i,v) {
            if(v==33){
                return;  //function里的return只是结束了当前的函数,并不会影响后面函数的执行
            }
            console.log(i,v);
        })
    </script>
    运行结果:
    0 11
    1 22
    3 44
    
    <script>
        li=[11,22,33,44];
        $.each(li,function (i,v) {
            if(v==33){
                return false;
            }
            console.log(i,v);
        })
    </script>
    运行结果:
    0 11
    1 22
    
    //考虑到我们的需求里有很多这样的情况:不管循环到第几个函数时,一旦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
    

    文档节点处理

    //创建一个标签对象
        var $p=$("<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]])
    

    动画效果

    显示隐藏

    <script src="../../jQuery/jquery-3.2.1.js"></script>
        <script>
            $(document).ready(function () {
                $("#hide").click(function () {
                    $("p").hide(1000);
                });
                $("#show").click(function () {
                    $("p").show(1000);
                });
    
                //用于切换被选元素的 hide() 与 show() 方法。
                $("#toggle").click(function () {
                    $("p").toggle();
                })
    
            })
        </script>
    </head>
    <body>
        <p>hello</p>
        <button id="hide">隐藏</button>
        <button id="show">显示</button>
        <button id="toggle">切换</button>
    </body>
    </html>
    

    滑动

        <script src="../../jQuery/jquery-3.2.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>
    </head>
    <body>
        <div id="content">hello world</div>
        <button id="slidedown">出现</button>
        <button id="slideup">隐藏</button>
        <button id="slidetoggle">切换</button>
    </body>
    </html>
    

    淡入淡出

        <script src="../../jQuery/jquery-3.2.1.js"></script>
        <script>
            $(document).ready(function () {
                $("#in").click(function () {
                    $("#content").fadeIn(1000);
                });
                $("#out").click(function () {
                    $("#content").fadeOut(1000);
                });
                $("#toggle").click(function () {
                    $("#content").fadeToggle(1000);
                });
                $("#fadeto").click(function () {
                    $("#content").fadeTo(1000,0.8);
                })
                
            })
        </script>
    </head>
    <body>
        <div id="content" style="display:none;200px;height:200px;background-color: #3D7FBB "></div>
        <button id="in">出现</button>
        <button id="out">隐藏</button>
        <button id="toggle">切换</button>
    
        <!--fadeTo()设置淡入淡出效果的不透明度-->
        <button id="fadeto">fadeto</button>
    </body>
    </html>
    

    回调函数

    <body>
        <button>hide</button>
        <p>hello world</p>
    
        <script>
            $("button").click(function () {
                $("p").hide(1000,function () {
                    alert($(this).html())
                })
            })
        </script>
    </body>
    

    css操作

    css位置操作

            $("").offset([coordinates])
            $("").position()
            $("").scrollTop([val])
            $("").scrollLeft([val])        
    
        <style>
            #box1{
                 200px;
                height: 200px;
                background-color: wheat;
            }
            #box2{
                 200px;
                height: 200px;
                background-color: palevioletred;
            }
        </style>
        <script src="../../jQuery/jquery-3.2.1.js"></script>
    </head>
    <body>
    <div id="box1"></div>
    <div id="box2"></div>
    <button id="offset">偏移</button>
    <script>
        $("#offset").click(function () {
            $("#box2").offset({left:200,top:200})
        });
        var $offset=$("#box2").offset();
        var lefts=$offset.left;
        console.log(lefts);
        var tops=$offset.top;
        console.log(tops);
    </script>
    
    </body>
    
        <style>
            *{
                margin:0;
                padding:0;
            }
            .box1{
                200px;
                height:200px;
                background-color: #09E0B5;
            }
    
            .box2{
                200px;
                height:200px;
                background-color:wheat;
            }
    
            /*----------*/
            .outer{
                position:relative;
            }
        </style>
        <script src="../../jQuery/jquery-3.2.1.js"></script>
    </head>
    <body>
        <div class="box1"></div>
        <div class="outer">
            <div class="box2"></div>
        </div>
        <script>
    //        console.log($(".box1").position().left);    //0
    //        console.log($(".box1").position().top); //0
    
    //        console.log($(".box2").position().left);    //0
    //        console.log($(".box2").position().top); //200
    
            //给.outer设置属性
            console.log($(".box2").position().left);    //0
            console.log($(".box2").position().top); //0
    
        </script>
    </body>
    </html>
    
        <style>
            *{
                margin:0
            }
            .outer{
                100%;
                height:1000px;
                background-color:darkgray;
            }
    
            .toTop{
                80px;
                height:40px;
                background-color: #09E0B5;
                color:navajowhite;
                text-align: center;
                line-height: 40px;
                position:fixed;
                bottom:10px;
                right:10px;
                display:none;
            }
        </style>
        <script src="../../jQuery/jquery-3.2.1.js"></script>
    </head>
    <body>
        <div class="outer">
            <div class="toTop">返回顶部</div>
        </div>
        <script>
            $(window).scroll(function () {
                console.log($(this).scrollTop());
                if($(this).scrollTop()>0){
                    $(".toTop").show();
                }
                else{
                    $(".toTop").hide()
                }
            });
            $(".toTop").click(function () {
                $(window).scrollTop(0)
            })
    
        </script>
    </body>
    </html>
    

    尺寸操作

            $("").height([val|fn])
            $("").width([val|fn])
            $("").innerHeight()
            $("").innerWidth()
            $("").outerHeight([soptions])
            $("").outerWidth([options])
    
        <style>
            *{
                margin:0
            }
            .box{
                100px;
                height:100px;
                background-color: #3D7FBB;
                padding:50px;
                border:10px solid lightcoral;
                margin:10px;
            }
        </style>
        <script src="../../jQuery/jquery-3.2.1.js"></script>
    </head>
    <body>
        <div class="box">hello world</div>
        <script>
            console.log($(".box").width()); //100
            console.log($(".box").height());    //100
    
            console.log($(".box").innerWidth());    //200
            console.log($(".box").innerHeight());   //200
    
            console.log($(".box").outerWidth());    //220
            console.log($(".box").outerHeight());   //220
    
            console.log($(".box").outerWidth(true));    //240
            console.log($(".box").outerHeight(true));   //240
        </script>
    </body>
    </html>
    
  • 相关阅读:
    Poj 1742 Coins(多重背包)
    Poj 2350 Above Average(精度控制)
    求二进制数中1的个数
    Poj 1659 Distance on Chessboard(国际象棋的走子规则)
    Poj 2411 Mondriaan's Dream(压缩矩阵DP)
    Poj 2136 Vertical Histogram(打印垂直直方图)
    Poj 1401 Factorial(计算N!尾数0的个数——质因数分解)
    poj 2390 Bank Interest(计算本利和)
    Poj 2533 Longest Ordered Subsequence(LIS)
    Poj 1887 Testing the CATCHER(LIS)
  • 原文地址:https://www.cnblogs.com/metianzing/p/7403990.html
Copyright © 2011-2022 走看看