前端基礎---jquery

1jQuery簡介

1   jQuery由美國人John Resig創建,至今已吸引了來自世界各地的衆多javascript高手加入其team

2   jQuery是繼prototype之後又一個優秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

3  它是輕量級的js(壓縮後只有21k) ,這是其它的js庫所不及的,它兼容CSS3,還兼容各種瀏覽器

4  jQuery是一個快速的,簡潔的javaScript庫,使用戶能更方便地處理HTMLdocumentsevents、實現動畫效果,並且方便地爲網站提供AJAX交互。

5  jQuery還有一個比較大的優勢是,它的文檔說明很全,而且各種應用也說得很詳細,同時還有許多成熟的插件可供選擇。

 

2jQuery對象

jQuery 對象就是通過jQuery包裝DOM對象後產生的對象。jQuery 對象是 jQuery 獨有的如果一個對象是 jQuery 對象那麼它就可以使用 jQuery 裏的方法

$("#test").html()   

        意思是指:獲取IDtest的元素內的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()          //jquery代碼實現

$("#msg")[0].innerHTML      //DOM代碼實現

 

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

1】選擇器

基本選擇器:

$("*")          通配符(全部)

$("#id")         id選擇器

$(".class")       class選擇器

$("element")     標籤選擇器

$(".class,p,div")   組合選擇器

 

層級選擇器:

$(".outer div")       後代元素選擇器

$(".outer>div")       子元素選擇器

$(".outer+div")       毗鄰元素選擇器

$(".outer~div")      普通兄弟選擇器

 

基本篩選器

$("li:first")        篩選第一個li標籤

$(“li:last”)       篩選最後一個li標籤

$("li:eq(2)")          篩選第3li標籤

$("li:even")         篩選排序爲奇數的li標籤(隔行篩選)

$("li:gt(1)")        篩選排序大於1li標籤

 

屬性選擇器

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

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

 

表單選擇器:只適用於表單標籤

$("[type='text']")     等同於$(":text")        

注意只適用於input標籤  : $("input:checked")

 

 

2】篩選器

過濾篩選器

$("li").eq(2)           篩選第2li標籤(推薦使用,方便傳參)

$("li").first()          篩選第1li標籤

$("ulli").hasclass("test")     篩選class中含有testulli標籤

 

查找篩選器

查找子標籤:        

$("div").children(".test")      //找兒子標籤的test

$("div").find(".test")         //找所有後代標籤中的test

向下查找兄弟標籤:   

$(".test").next() $(".test").nextAll()     

$(".test").nextUntil()      //開區間查找,不含尾

向上查找兄弟標籤:   

$("div").prev()      $("div").prevAll()      $("div").prevUntil()  

查找所有兄弟標籤:   

$("div").siblings()               

查找父標籤:

$(".test").parent()             

$(".test").parents()           找所有父標籤,到html

$(".test").parentUntil(“.outer”)    查找父標籤(不含outer

 

4、文本操作

Jquery事件綁定

$(“.p1”).click(function (){

      alert(123)

})

 

練習:

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

<p class="p1">P1</p>
<p class="p1">P2</p>
<p class="p1">P3</p>
<p class="p1">p4</p>

<script>
    // DOM對象轉爲Jquery對象  $(DOM對象)
    $("p").click(function () {
        console.log($(this));

        // 取值操作
        //alert($(this).html());
        //alert($(this).text())

        // 賦值操作
        $(this).html("<a href=''>hello</a>")
        //$(this).text("<a>hello</a>")
    })

</script>

</body>
</html>


5、操作元素

a. Jquery事件

頁面載入

ready(fn)          // DOM載入就緒可以查詢及操縱時綁定一個要執行的函數。

$(document).ready(function(){})-----------> $(function(){})

 

事件綁定

$(“.p1”).click(function (){

      alert(123)

})

練習:

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

<p class="p1">P1</p>
<p class="p1">P2</p>
<p class="p1">P3</p>
<p class="p1">p4</p>

<script>
    // DOM對象轉爲Jquery對象  $(DOM對象)
    $("p").click(function () {
        console.log($(this));

        // 取值操作
        //alert($(this).html());
        //alert($(this).text())

        // 賦值操作
        $(this).html("<a href=''>hello</a>")
        //$(this).text("<a>hello</a>")
    })

</script>

</body>
</html> 
事件委派


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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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.1.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)

    });

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

</script>

</body>
</html>

 

事件切換

hover事件

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

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

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

 

b.屬性操作

--------------------------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方法去操作才能獲得正確的結果。


//    $("#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>


c.each循環

jquery支持兩種循環方式:

方式一:

格式:$.each(obj,fn)

li=[10,20,30,40];
dic={name:"yuan",sex:"male"};
$.each(li,function(i,x){
    console.log(i,x)
});

方式二:

格式:$("").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
//---------------------------------------------------------------------


d.文檔節點處理

//創建一個標籤對象

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

 

e.動畫效果

顯示隱藏

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script src="jquery-2.1.4.min.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>
   <link type="text/css" rel="stylesheet"href="style.css">
</head>
<body>
   <p>hello</p>
   <button id="hide">隱藏</button>
   <button id="show">顯示</button>
   <button id="toggle">切換</button>
</body>
</html>


滑動:

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script src="jquery-2.1.4.min.js"></script>
   <script>
   $(document).ready(function(){
    $("#slideDown").click(function(){
        $("#content").slideDown(1000);
    });
     $("#slideUp").click(function(){
        $("#content").slideUp(1000);
    });
     $("#slideToggle").click(function(){
        $("#content").slideToggle(1000);
    })
  });
   </script>
   <style>
 
       #content{
           text-align: center;
           background-color: lightblue;
           border:solid 1px red;
           display: none;
           padding: 50px;
       }
   </style>
</head>
<body>
 
   <div id="slideDown">出現</div>
   <div id="slideUp">隱藏</div>
   <div id="slideToggle">toggle</div>
 
   <div id="content">helloworld</div>
 
</body>
</html>


淡入淡出:

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script src="jquery-2.1.4.min.js"></script>
   <script>
   $(document).ready(function(){
  $("#in").click(function(){
      $("#id1").fadeIn(1000);
 
 
  });
   $("#out").click(function(){
      $("#id1").fadeOut(1000);
 
  });
   $("#toggle").click(function(){
      $("#id1").fadeToggle(1000);
 
 
  });
   $("#fadeto").click(function(){
      $("#id1").fadeTo(1000,0.4);
 
  });
});
 

   </script>
 
</head>
<body>
     <button id="in">fadein</button>
     <button id="out">fadeout</button>
     <button id="toggle">fadetoggle</button>
     <button id="fadeto">fadeto</button>
 
     <div id="id1" style="display:none; width: 80px;height:80px;background-color: blueviolet"></div>
 
</body>
</html>

 

回調函數:

<!DOCTYPE html>
<html>
<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>


f.css操作

css位置操作

$("").offset([coordinates])

$("").position()

$("").scrollTop([val])

$("").scrollLeft([val])

 

練習1

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
       .test1{
           width: 200px;
           height: 200px;
           background-color: wheat;
       }
   </style>
</head>
<body>
 
 
<h1>this is offset</h1>
<divclass="test1"></div>
<p></p>
<button>change</button>
</body>
<scriptsrc="jquery-3.1.1.js"></script>
<script>
   var $offset=$(".test1").offset();
   var lefts=$offset.left;
   var tops=$offset.top;
 
   $("p").text("Top:"+tops+" Left:"+lefts);
   $("button").click(function(){
 
       $(".test1").offset({left:200,top:400})
   })
</script>
</html>


練習2

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>Title</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>
 
 
 
 
<divclass="box1"></div>
<div>
   <div></div>
</div>
<p></p>
 
 
<scriptsrc="jquery-3.1.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>
<head>
   <meta charset="UTF-8">
   <title>Title</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: darkgrey;
           height: 2400px;
       }
 
 
       .hide{
           display: none;
       }
   </style>
</head>
<body>
    <div class="div1 div">
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
          <h1>hello</h1>
     </div>
    <div class="div2 div"></div>
    <div class="returnTop hide">返回頂部</div>
 
 <scriptsrc="jquery-3.1.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>


尺寸操作

$("").height([val|fn])

$("").width([val|fn])

$("").innerHeight()

$("").innerWidth()

$("").outerHeight([soptions])

$("").outerWidth([options])

 

練習:

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
       *{
           margin: 0;
       }
       .box1{
           width: 200px;
           height: 200px;
            background-color: wheat;
           padding: 50px;
           border: 50px solid rebeccapurple;
           margin: 50px;
       }
   </style>
</head>
<body>
 
<div>
   DIVDIDVIDIV
</div>
 
<p></p>
<scriptsrc="jquery-3.1.1.js"></script>
<script>
   var $height=$(".box1").height();
   var $innerHeight=$(".box1").innerHeight();
   var $outerHeight=$(".box1").outerHeight();
   var $margin=$(".box1").outerHeight(true);
 
   $("p").text($height+"---"+$innerHeight+"-----"+$outerHeight+"-------"+$margin)
</script>
</body>
</html>


Jquery擴展方法(插件機制)

jQuery.extend(object)

擴展jQuery對象本身,用來在jQuery命名空間上增加新函數

練習:

jQuery命名空間上增加兩個函數

<script>
   jQuery.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">
 
<scriptsrc="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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章