前端學習之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 對象, 那么要在變量前面加上$.
        var $variable = jQuery 對象
        var variable = DOM 對象

基本語法:$(selector).action() 

jQuery 語法是通過選取 HTML 元素,並對選取的元素執行某些操作。
    美元符號定義 jQuery
    選擇符(selector)"查詢"和"查找" HTML 元素
  jQuery 的 action() 執行對元素的操作
  實例:
  $(this).hide() - 隱藏當前元素
  $("p").hide() - 隱藏所有 <p> 元素
  $("p.test").hide() - 隱藏所有 class="test" 的 <p> 元素
  $("#test").hide() - 隱藏所有 id="test" 的元素

    開始使用JQuery,首先引用JQ插件

<script src="jquery-3.1.1.js"></script>

二 、尋找元素(重要的選擇器和篩選器)     

選擇器     

基本選擇器 :$("*")       所有元素
$("#id") 例如:$("#id") id="id1" 的元素
$(".class") 例如:$(".intro") 所有 class="intro" 的元素
$("element") 例如:$("p") 所有 <p> 元素
$(".class,p,div") 層級選擇器 :$(".outer div") $(".outer>div") $(".outer+div") $(".outer~div") 基本篩選器 :$("li:first") 第一個 <li> 元素
$("li:eq(2)") 列表中的第2個元素(index 從 0 開始)
$("li:even") 所有偶數 <li> 元素
$("li:gt(1)") 列出 index 大於 1 的元素 屬性選擇器 :$('[id="div1"]') $('["alex="sb"][id]') 表單選擇器 :$("[type='text']")----->$(":text") (簡寫) 注意只適用於input標簽 $("input:checked")

篩選器

過濾篩選器: $("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()
    $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 
    $("div").siblings() //獲取div標簽的兄弟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.1.1.js"></script>
    <style>
        .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              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" onclick="show(this);">菜單一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜單二</div>
            <div class="con hide">
                <div>222</div>
                <div>222</div>
                <div>222</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜單三</div>
            <div class="con hide">
                <div>333</div>
                <div>333</div>
                <div>333</div>
            </div>
        </div>

    </div>
    <div class="content"></div>

</div>

</body>
<script>
          function show(self){
//              console.log($(self).text())
              $(self).next().removeClass("hide") //去除選中標簽的下一個標簽的hide樣式 例如選中菜單二標簽,就是讓<div>222</div>顯示
              $(self).parent().siblings().children(".con").addClass("hide")

          }
    </script>
</html>
左側菜單例子
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <script src="jquery-3.1.1.js"></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;
        }
        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }

         .hide{
            display: none;
        }

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

<script>
    function tab(self) {
       $(self).addClass("current");
       $(self).siblings().removeClass("current");
       var s=$(self).attr('xxx'); //attr 設置或返回被選元素的屬性值。當點擊菜單一時 s="c1"
       $("#"+s).removeClass("hide").siblings().addClass("hide");// "#"+s為字符串拼接=#c1 即$("#"+s)=$(#c1)  jquery選中的標簽去除hide他的兄弟標簽添加hide

       }

</script>

</html>
tab切換

三  、操作元素(屬性 CSS 和 文檔處理) 

屬性操作

$("p").text()    $("p").html()   $(":checkbox").val()
$(".test").attr("alex")   $(".test").attr("alex","sb") 
$(".test").attr("checked","checked")  $(":checkbox").removeAttr("checked")
$(".test").prop("checked",true)
$(".test").addClass("hide")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.1.1.js"></script>
</head>
<body>
 <button onclick="selectall();">全選</button>
     <button onclick="che();">取消</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>

<script>

     function selectall(){
                 $("table :checkbox").prop("checked",true)
             }
      function che(){
                 $("table :checkbox").prop("checked",false)
             }

     function reverse(){
               //each() 方法規定為每個匹配元素規定運行的函數。
               $("table :checkbox").each(function(){
                     if ($(this).prop("checked")){
                         $(this).prop("checked",false)
                     }
                     else {
                         $(this).prop("checked",true)
                     }

                 });
</script>
</html>
正反選

CSS操作

(樣式)   css("{color:'red',backgroud:'blue'}") 
(位置)   offset()    position()  scrollTop()  scrollLeft()    
(尺寸)   height()  width()  
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.1.1.js"></script>
    <script>


          window.onscroll=function(){

              var current=$(window).scrollTop();
              console.log(current)
              if (current>100){

                  $(".returnTop").removeClass("hide")
              }
              else {
              $(".returnTop").addClass("hide")
          }
          }


           function returnTop(){
//               $(".div1").scrollTop(0);

               $(window).scrollTop(0)
           }




    </script>
    <style>
        body{
            margin: 0px;
        }
        .returnTop{
            height: 60px;
            width: 100px;
            background-color: darkgray;
            position: fixed;
            right: 0;
            bottom: 0;
            color: greenyellow;
            line-height: 60px;
            text-align: center;
        }
        .div1{
            background-color: orchid;
            font-size: 5px;
            overflow: auto;
            width: 500px;
        }
        .div2{
            background-color: darkcyan;
        }
        .div3{
            background-color: aqua;
        }
        .div{
            height: 300px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
     <div class="div1 div">
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>

     </div>
     <div class="div2 div"></div>
     <div class="div3 div"></div>
     <div class="returnTop hide" onclick="returnTop();">返回頂部</div>
</body>
</html>
返回頂部
<!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-3.1.1.js"></script>
<script>

      function action1(self) {
          $(self).parent().siblings().removeClass("hide");
      }

       function action2(self) {
          $(self).parent().parent().children(".shade,.models").addClass("hide")
      }
//    function action(act){
//        var ele=document.getElementsByClassName("shade")[0];
//        var ele2=document.getElementsByClassName("models")[0];
//        if(act=="show"){
//              ele.classList.remove("hide");
//              ele2.classList.remove("hide");
//        }else {
//              ele.classList.add("hide");
//              ele2.classList.add("hide");
//        }

//    }
</script>
</body>
</html>
模態對話框

文檔處理

內部插入  $("#c1").append("<b>hello</b>")     $("p").appendTo("div")
              prepend()    prependTo()

外部插入  before()  insertBefore()  after insertAfter()
             replaceWith()   remove()  empty()  clone()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
            <div class="outer">
                <div class="condition">

                        <div class="icons" style="display:inline-block">
                            <a onclick="add(this);"><button>+</button></a>
                        </div>

                        <div class="input" style="display:inline-block">
                            <input type="checkbox">
                            <input type="text" value="alex">
                        </div>
                </div>
            </div>

<script src="jquery-3.1.1.js"></script>
    <script>

            function add(self){
                var $duplicate = $(self).parent().parent().clone();
                $duplicate.find('a[onclick="add(this);"]').attr('onclick',"removed(this)").children("").text("-");
                $duplicate.appendTo($(self).parent().parent().parent());

            }
           function removed(self){

               $(self).parent().parent().remove()

           }

    </script>
</body>
</html>
clone例子

 

scrollTop()使用

scrollTop() 方法設置或返回被選元素的垂直滾動條位置。當滾動條位於最頂部時,位置是 0。

返回 <div> 元素的垂直滾動條位置:
$("button").click(function(){
    alert($("div").scrollTop());
});

返回滾動條距窗口頂部距離
$(window).scrollTop();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .back{
            position: fixed;
            bottom: 0px;
            right: 0px;
            background-color: red;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>

<div style="height: 1000px;border: 1px solid #ddd;color: yellow;">
    <div id="title" style="background-color: black;height: 40px;color: white;">
            標題
        </div>
</div>

<div onclick="GoTop()" class="back hide">返回頂部</div>

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

    function GoTop(){
        //返回頂部
        $(window).scrollTop(0);
    }

    $(function(){

        $(window).scroll(function(){
            //當滾動滑輪時,執行函數體

            //獲取當前滑輪滾動的高度
            var top = $(window).scrollTop();

            if(top>40){
                //展示“返回頂部”
                $('.back').removeClass('hide');
            }else{
                //隱藏“返回頂部”
                $('.back').addClass('hide');
            }
        });
    });

</script>

</body>
</html>
scrollTop例子
$(function(){/*...*/});是$(document).ready(function(){/*...*/})的簡寫形式,是在DOM加載完成后執行的回調函數,並且只會執行一次。
小知識

 擴展方法

     1.類方法($.extend())

<script> 
      $.extend({
        fun1:function(name){            //fun1是自己定義的函數名字,括號中的name是參數
            console.log(name)
        }
    });
     $.fun1("") ;                           //調用時直接$.函數名(參數);
</script> 

      2.對象方法($.fn.extend())

<body>
    <input type="text">
    <script>
            $.fn.extend({
            getMax:function(a,b){
                var result=a>b?a:b;
                console.log(result);
            }
        });
        $("input").getMax(1,2);        //調用時要$(標簽名).函數名();
    </script>
</body>

     3.一般情況下,jQuery的擴展方法寫在自執行匿名函數中(原因:在js中是以函數為作用域的,在函數中寫可以避免自己定義的函數或者變量與外部沖突)

<script>
    (function(){
        $.extent({
            print1:function(){
            console.log(123);
            }
        })
    })();
</script>     


說明:
f=function () {
    alert(123)
};
f();

上面的等同於
(function (a) {
   alert(a)
})(234);

 Jquery事件綁定

    DOM下兩種事件綁定方式

第一種
<p id="p1" onclick="fun1(this)">hello p</p>

function fun1(self) {
    alert(self.innerHTML);
}

第二種

var ele = document.getElementsByClassName("p")[0];
    ele.onclick=function () {
    alert(this.innerHTML)
   }

    Jquery事件綁定用click

<script>

        $("p").click=function () {
            $(this).css("color","red")
        }

</script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--<script>-->
<!--//       $(document).ready(function () {-->
<!--//           $("p").css("color","red")-->
<!--//       })-->

        <!--//簡寫方式:-->
<!--//        $(function () {-->
<!--//            $("p").css("color","red")-->
<!--//        })-->
<!--//    </script>-->


</head>
<body>
<p>hello world</p>


<ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
</ul>

<input type="button" value="+" onclick="add();">
<script src="jquery-2.1.4.min.js"></script>
<script>

//    $("p").click(function () {
//        alert(123)
//    })


//      $("p").bind("click",function () {
//          alert(123)
//      })

//    $("ul li").click(function () {
//            alert(456);
//    })
//    ---------等同於bind方法--------
//    $("ul li").on("click",function () {
//         alert(456);
//    });

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

    function add() {
        $("ul").append("<li>555</li>")
    }

  


</script>
</body>
</html>
例子

 

滾動菜單示例

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>

        body{
            margin: 0px;
        }
        img {
            border: 0;
        }
        ul{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        .wrap{
            width: 980px;
            margin: 0 auto;
        }

        .pg-header{
            background-color: #303a40;
            -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            box-shadow: 0 2px 5px rgba(0,0,0,.2);
        }
        .pg-header .logo{
            float: left;
            padding:5px 10px 5px 0px;
        }
        .pg-header .logo img{
            vertical-align: middle;
            width: 110px;
            height: 40px;

        }
        .pg-header .nav{
            line-height: 50px;
        }
        .pg-header .nav ul li{
            float: left;
        }
        .pg-header .nav ul li a{
            display: block;
            color: #ccc;
            padding: 0 20px;
            text-decoration: none;
            font-size: 14px;
        }
        .pg-header .nav ul li a:hover{
            color: #fff;
            background-color: #425a66;
        }
        .pg-body{

        }
        .pg-body .catalog{
            position: absolute;
            top:60px;
            width: 200px;
            background-color: #fafafa;
            bottom: 0px;
        }
        .pg-body .catalog.fixed{
            position: fixed;
            top:10px;
        }

        .pg-body .catalog .catalog-item.active{
            color: #fff;
            background-color: #425a66;
        }

        .pg-body .content{
            position: absolute;
            top:60px;
            width: 700px;
            margin-left: 210px;
            background-color: #fafafa;
            overflow: auto;
        }
        .pg-body .content .section{
            height: 500px;
        }

         img{
            width: 40px;
            height: 40px;
            margin-top: 4px;
            border-radius: 50%; /*給元素的圓角邊框*/
        }
    </style>
</head>
<body>

    <div class="pg-header">
        <div class="wrap clearfix">
            <div class="logo">
                <a href="#">
                    <img src="dva01.jpg">
                </a>
            </div>
            <div class="nav">
                <ul>
                    <li>
                        <a  href="#">首頁</a>
                    </li>
                    <li>
                        <a  href="#">功能一</a>
                    </li>
                    <li>
                        <a  href="#">功能二</a>
                    </li>
                </ul>
            </div>

        </div>
    </div>
    <div class="pg-body">
        <div class="wrap">
            <div class="catalog">
                <div class="catalog-item" auto-to="function1"><a>第1張</a></div>
                <div class="catalog-item" auto-to="function2"><a>第2張</a></div>
                <div class="catalog-item" auto-to="function3"><a>第3張</a></div>
            </div>
            <div class="content">
                <div menu="function1" class="section">
                    <h1>第一章</h1>
                </div>
                <div menu="function2" class="section">
                    <h1>第二章</h1>
                </div>
                <div menu="function3" class="section">
                    <h1>第三章</h1>
                </div>
            </div>
        </div>

    </div>

    <script type="text/javascript" src="jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        $(function(){
            Init();
        });
        function Init(){
            $(window).scroll(function() {
                var scrollTop = $(window).scrollTop();
                if(scrollTop > 50){
                    $('.catalog').addClass('fixed');
                }else{
                    $('.catalog').removeClass('fixed');
                }
                $('.content').children().each(function(){
                    var offSet = $(this).offset();
                    var offTop = offSet.top - scrollTop;
                    var height = $(this).height();

                    if(offTop<=0 && offTop> -height){
                        //去除其他
                        //添加自己
                        var docHeight = $(document).height();
                        var winHeight = $(window).height();

                        if(docHeight == winHeight+scrollTop)
                        {
                            $('.catalog').find('div:last-child').addClass('active').siblings().removeClass('active');
                        }else{
                            var target = $(this).attr('menu');
                            $('.catalog').find('div[auto-to="'+target+'"]').addClass('active').siblings().removeClass('active');
                        }


                    }
                });

            });


        }

    </script>
</body>
</html>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM