jQuery基礎學習

1、簡介

  jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype以後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是「Write Less, Do More」,即倡導寫更少的代碼,作更多的事情。它封裝JavaScript經常使用的功能代碼,提供一種簡便的JavaScript設計模式,優化HTML文檔操做、事件處理、動畫設計和Ajax交互。css

  jQuery的核心特性能夠總結爲:具備獨特的鏈式語法和短小清晰的多功能接口;具備高效靈活的css選擇器,而且可對css選擇器進行擴展;擁有便捷的插件擴展機制和豐富的插件。jQuery兼容各類主流瀏覽器,如IE 6.0+、FF 1.5+、Safari 2.0+、Opera 9.0+等。html

2、jQuery是什麼?

  ·jQuery是由美國人John Resig建立,至今已吸引了來自世界各地的衆多JavaScript高手加入其中。jquery

  ·jQuery是繼prototype以後又一個優秀的JavaScript框架。其宗旨是——Write Less, Do More!css3

  ·jQuery是輕量級的js庫,這是其它的js庫所不及的,它兼容css3,還兼容各類瀏覽器。設計模式

  ·jQuery是一個快速的,簡潔的JavaScript庫,使用戶能更方便地處理HTML documents、events、實現動畫效果,而且方便地爲網站提供AJAX交互。數組

  ·jQuery還有一個比較大的優點是,它的文檔說明很全,並且各類應用也說得很詳細,同時還有許多成熟的插件可供選擇。瀏覽器

3、什麼是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()app

4、尋找元素(選擇器和篩選器)

4.1 選擇器

  4.1.1 基本選擇器框架

$("*")dom

$("#id")

$(".class")

$(".class, p, div")

  4.1.2 層級選擇器

$(".outer div")

$(".outer>div")

$(".outer+div")

$(".outer~div")

  4.1.3 基本篩選器

$("li:first")

$("li:eq(2) ")

$("li:even")

$("li:gt(1) ")

  4.1.4 屬性選擇器

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

$('[name="mayi"]')

  4.1.5 表單選擇器

$("[type='text']") ----->$(":text")  注意:只適用於input標籤:$("input:checked")

  4.1.6 表單屬性選擇器

:enabled

:disabled

:checked

:selected

  例子:

<body>
<form>
    <label>123<input type="checkbox" value="123" checked /></label>
    <label>456<input type="checkbox" value="456" checked /></label>

    <label>植物
        <select>
            <option value="1">Flowers</option>
            <option value="2">Garends</option>
            <option value="3">Trees</option>
        </select>
    </label>
</form>

<script src="jquery-3.4.1.js"></script>
<script>
    // console.log($("input:checked").length); //2

    $("input:checked").each(function(){
        console.log($(this).val())
    })
</script>
</body>

4.2 篩選器

  4.2.1 過濾篩選器

$("li").eq(2)

$("li").first()

$("ul li").hasclass("test")

  4.2.2 查找篩選器

查找子標籤

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

5、操做元素(屬性、css、文檔處理)

5.1 事件

  頁面載入

ready(fn);  //當DOM載入就緒能夠查詢及操做時綁定一個要執行的函數。
$(document).ready(function(){}); //-----> $(function(){})  

  事件綁定

//語法:標籤對象.事件(函數)
$("p").click(function(){});

  事件委派

//在選擇元素上綁定一個或多個事件的事件處理函數。
$("").on(eve, [selector], [data], fn);

  例子:

<body>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<hr>
<button id="add_li">Add_li</button>
<button id="off">off</button>

<script src="jquery-3.4.1.js"></script>
<script>
    $("ul li").click(function(){
        alert(123);
    });

    $("#add_li").click(function(){
        var $ele = $("<li>");
        $ele.text(Math.round(Math.random() * 10));
        $("ul").append($ele);
    });

//    $("ul").on("click", "li", function(){
//        alert(456);
//    });

    $("#off").click(function(){
        $("ul li").off();
    });

</script>
</body>

  事件切換

  hover事件:一個模仿懸停事件(鼠標移動到一個對象上面及移出這個對象)的方法。這是一個自定義的方法,它爲頻繁使用的任務提供了一種「保持在其中」的狀態。

  over事件:鼠標移到元素上要觸發的函數。

  out事件:鼠標移出元素要觸發的函數。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test03</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .test {
            width: 200px;
            height: 200px;
            background-color: wheat;
        }
    </style>
</head>
<body>
<div class="test"></div>

<script src="jquery-3.4.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>
</body>
</html>

5.2 屬性操做

//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方法使用:

<body>
<label><input id="chk1" type="checkbox" />是否可見</label>
<label><input id="chk2" type="checkbox" checked="checked" />是否可見</label>
<script src="jquery-3.4.1.js"></script>
<script>
    //對於HTML元素自己就帶有的固有屬性,在處理時,使用prop方法。
    //對於HTML元素咱們自定義的DOM屬性,在處理時,使用attr方法。
    //像checkbox, radio和select這樣的元素,選中屬性對應「checked」和「selected」,這
    // 些也屬於固有屬性,所以須要使用prop方法去操做纔有得到正確的結果。

    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>
</body>

5.3 each循環

  咱們知道$("p").css("color", "red")是將css操做加到全部的標籤上,內部維持一個循環;但若是對於選中標籤進行不一樣處理,這時就須要對全部標籤數組進行循環遍歷了。

  jQuery支持兩種循環方式:

  方式一:

  格式:$.each(obj, fn)

li = [10, 20, 30, 40];
dic = {name: "MaYi", sex: "male"};

$.each(li, function(i, x){
    console.log(i, x);
});

$.each(dic, function(k, v){
    console.log(k, v);
});

  方式二:

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

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

  其中,$(this)代指當前循環標籤。

5.4 文檔節點處理

  建立一個標籤對象

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

$("p").before("<b>Hello</b>");

 

 

$("").insertAfter(content|fn)

$("p").insertAfter("#foo");

 

 

$("").insertBefore(content)

$("p").insertBefore("#foo");

 

 

  替換

$("").replaceWith(content|fn)

$("p").replaceWith("<b>Paragraph.</b>");

  刪除

$("").empty()

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

  複製

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

5.5 動畫效果

  顯示隱藏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<p>hello</p>
<button id="hide">隱藏</button>
<button id="show">顯示</button>
<button id="toggle">切換</button>

<script src="jquery-3.4.1.js"></script>
<script>
    $("#hide").click(function(){
        $("p").hide(1000);  //1000毫秒
    });

    $("#show").click(function(){
        $("p").show(1000);  //1000毫秒
    });

    $("#toggle").click(function(){
        $("p").toggle(1000);  //1000毫秒
    });
</script>
</body>
</html>

  滑動

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <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">切換</div>
<div id="content">hello world!</div>

<script src="jquery-3.4.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>
</body>
</html>

  淡入淡出

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        #id1 {
            display: none;
            width: 80px;
            height: 80px;
            background-color: blueviolet;
        }
    </style>
</head>
<body>
<button id="in">fade in</button>
<button id="out">fade out</button>
<button id="toggle">fade toggle</button>
<button id="to">fade to</button>
<div id="id1"></div>

<script src="jquery-3.4.1.js"></script>
<script>
    $("#in").click(function(){
        $("#id1").fadeIn(1000);
    });

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

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

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

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

  回調函數

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<button>hide</button>
<p>hello world</p>
<script src="jquery-3.4.1.js"></script>
<script>
    $("button").click(function(){
        $("p").hide(1000, function(){
            alert($(this).html());
        });
    });

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

5.6 css操做

  css位置操做

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

  示例1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        .test {
            width: 200px;
            height: 200px;
            background-color: wheat;
        }
    </style>
</head>
<body>
<h1>this if offset</h1>
<div class="test"></div>
<p></p>
<button>change</button>

<script src="jquery-3.4.1.js"></script>
<script>
    var $offset = $(".test").offset();
    var $lefts = $offset.left;
    var $tops = $offset.top;

    $("p").text("Top:" + $tops + " Left:" + $lefts);
    $("button").click(function(){
        $(".test").offset({left: 200, top: 400});
    });

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

  示例2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        * {
            margin: 0;
        }

        .box1 {
            width: 200px;
            height: 200px;
            background-color: rebeccapurple;
        }

        .box2 {
            width: 200px;
            height: 200px;
            background-color: darkcyan;
        }

        .parent_box {
            position: relative;
        }
    </style>
</head>
<body>
<div class="box1">hello box1</div>
<div class="parent_box">
    <div class="box2">hello box2</div>
</div>
<p>hello p</p>

<script src="jquery-3.4.1.js"></script>
<script>
    var $position = $(".box2").position();
    var $left = $position.left;
    var $top = $position.top;

    $("p").text("Top:" + $top + " Left:" + $left);

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

  示例3:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        body {
            margin: 0;
        }

        .returnTop {
            height: 60px;
            width: 100px;
            background-color: peru;
            position: fixed;
            right: 0;
            bottom: 0;
            color: white;
            line-height: 60px;
            text-align: center;
        }

        .div1 {
            background-color: wheat;
            font-size: 5px;
            overflow: auto;
            width: 500px;
            height: 200px;
        }

        .div2 {
            background-color: darkgray;
            height: 2400px;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>
<div class="div1 div">
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
</div>
<div class="div2 div">hello div2</div>
<div class="returnTop hide">返回頂部</div>

<script src="jquery-3.4.1.js"></script>
<script>
    $(window).scroll(function(){
        var $current = $(window).scrollTop();
        console.log($current);
        if($current > 100){
            $(".returnTop").removeClass("hide");
        }
        else{
            $(".returnTop").addClass("hide");
        }
    });

    $(".returnTop").click(function(){
        $(window).scrollTop(0);
    });

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

  css尺寸操做

$("").height([val|fn])
$("").width([val|fn])
$("").innerHeight()
$("").innerWidth()
$("").outerHeight([soptions])
$("").outerWidth([options])

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        * {
            margin: 0;
        }

        .box1 {
            width: 200px;
            height: 200px;
            background-color: wheat;
            padding: 50px;
            border: 50px solid rebeccapurple;
            margin: 50px;
        }
    </style>
</head>
<body>
<div class="box1">
    hello div
</div>
<p>hello p</p>

<script src="jquery-3.4.1.js"></script>
<script>
    var $ele = $(".box1");
    var $height = $ele.height();
    var $innerHeight = $ele.innerHeight();
    var $outerHeight = $ele.outerHeight();
    var $margin = $ele.outerHeight(true);

    //200---300---400---500
    $("p").text($height + "---" + $innerHeight + "---" + $outerHeight + "---" + $margin);

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

6、擴展方法(插件機制)

6.1 jQuery.extend(object)

  擴展jQuery對象自己。

  用來在jQuery命名空間上增長新函數。

  例:在jQuery命名空間上增長兩個函數:

<script src="jquery-3.4.1.js"></script>
<script>
    jQuery.extend({
        min: function(a, b) { return a < b ? a : b;},
        max: function(a, b) { return a > b ? a : b;}
    });

    console.log(jQuery.min(2, 3));  //2
    console.log(jQuery.max(4, 5));  //5
</script>

6.2 jQuery.fn.extend(object)

  擴展jQuery元素集來提供新的方法(一般用來製做插件)。

  例:增長兩個插件方法:

<body>
<label><input type="checkbox" /></label>
<label><input type="checkbox" /></label>
<label><input type="checkbox" /></label>

<script src="jquery-3.4.1.js"></script>
<script>
    jQuery.fn.extend({
        check: function(){
            $(this).attr("checked", true);
        },
        uncheck: function(){
            $(this).attr("checked", false);
        }
    });

    $(":checkbox:gt(0)").check();

</script>
</body>
相關文章
相關標籤/搜索