1. 程式人生 > >前端基礎之jQuery

前端基礎之jQuery

它的 是否 屬性選擇器 mat fadein form 內部 ops -html

概述

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{

            width: 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{

            width: 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;width: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{
            width: 200px;
            height: 200px;
            background-color: wheat;
        }
        #box2{
            width: 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{
            width:200px;
            height:200px;
            background-color: #09E0B5;
        }

        .box2{
            width: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{
            width:100%;
            height:1000px;
            background-color:darkgray;
        }

        .toTop{
            width: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{
            width: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>

前端基礎之jQuery