jQuery常用方法和練習例子

要點:

    1、jQuery方法內置循環:

            $('div').css('backgroundColor','red'):給所有DIV標籤添加紅色背景

    2、this出現在jQuery的function中,代表循環時,當前正在處理的DOM對象

    3、$(this),把當前DOM對象轉換在JQuery,以便使用jQuery方法

    4、隱式條件判斷語句:

                var result=條件表達式?真返回值:假返回值;

    5、each(function) 對象的每個元素都做操作。

    收藏:jQuery樣式。https://www.layui.com/demo/rate.html

常用方法:

    1、篩選器:

    next('篩選條件')    當前的下一個

    nextAll('篩選條件')    當前的後面所有

    nextUntil('篩選條件')    從下一個,到滿足'篩選條件'的前一個標籤,

    prev('篩選條件')    當前的上一個

    prevAll('篩選條件')    當前位置前面的所有同級標籤

    prevUntil('篩選條件')    從上一個,到滿足‘篩選條件’的前一個標籤

    parent('篩選條件')    父標籤

    parents('篩選條件')    向上一直找,直到html

    parentsUntil('篩選條件')    向上一直找到'滿足篩選條件的標籤'

    children('篩選條件')    子標籤

    siblings('篩選條件')    除自已外,其它兄弟標籤

    find('篩選條件')        遍歷自已包含的所有標籤,找到‘符合條件的所有標籤’

    first()                    結果裏的第一個

    last()                    結果裏的最後一個

    eq(數值)/ eq('數值')        結果的表列裏,第幾個值


    2、內容方法:

        text()     取值/賦值,無參數,獲取文本內容;text('this a text'),賦值

        html()    取值/賦值,無參數,獲取文本內容;text('<p>this is a html</p>'),賦值

        val()       input標籤,取值/賦值,無參數,獲取value;val('value新值'),賦值。jQuery版本3以前,checkbox和radio會出現不同步,必須使用prop        

        prop(屬性,值)    設置或返回被選元素的屬性和值。使用字典同時多值,設置:prop('checked','checked'),獲取屬性值:prop('checked'),結果undefine,代表沒有此屬性。

        attr(屬性,值)      設置被選元素的屬性和值。可以接受字典值。

        prop與attr區別:prop  對於HTML元素本身就帶有的固有屬性   attr  對於HTML元素我們自定義的加在標籤中的屬性。  

        具有 true 和 false 兩個屬性的屬性,如 checked, selected 或者 disabled 使用prop()

       

    $("img").attr("width",function(n,v){        \\n當前對象在篩選器裏的索引,v是獲取到width的值。
      return v-50;
    });
    
    <img src='https://static2.51cto.com/51cto/cms/homepage/2015/images/logo.gif' width='500px' />

                    

    3、樣式方法:

        hasClass('樣式名')            判斷是否包含樣式名

        addClass('樣式名'):          添加calss樣式

        removeClass('樣式名'):    刪除class樣式

        toggleClass('樣式名'):     不存在則添加,存在則刪除

        

    4、文檔處理:

        append(htmlstring) :在指定標籤內部的最後添加內容

        prepend(htmlstring):在指定標籤內部的最前面添加內容

        after(htmlstring):在指定標籤結束符後,外面添加

        before(htmlstring):在指定標籤開始符前,外面添加

        remove():刪除當前元素

        empty():清空所有子元素

        clone():返回複製的元素html

      //添加
      $('#s1').click(function(){
        var s='<li>我是新來的</li>';
        $('#uli').after(s)
      })
      //remove()
      $('#r1').click(function(){
      $('#uli').remove();)}
      
      //empty();清空所有子元素
     $('#e1').click(function(){
       $('#uli').empty();
     })
     //clone,複製id=uli的元素,並追加到body
     $('body').append($('#uli').clone())

    5、鼠標座標

        scrollTop(值) 設置/獲取當前對象的滾動條上下位置。

        scrollLeft(值) 設置/獲取當前對象的滾動務左右位置。

        

        offset().left    獲取元素左上角的當前X座標

        offset().top    獲取元素左上角的當前Y座標

        offset({left:0,top:0})        設置當前元素的座標

        event.x    獲取鼠標當前X座標

        event.y    獲取鼠標當前Y座標

      $(document.body).mousemove(function(){
        $('#xx').text(event.x);
        $('#yy').text(event.y);
      })
      
      $('#divmove').offset({left:100,top:100})

    6、jQuery綁定四種事件。

        直接綁定:.click

        bind綁定:

            $('c1').bind('click',function(){....})

        delegate/undelegate綁定:在jQuery1.7中 .delegate()已被.on()取代

            $('c1').delegate('a','click',function(){ .... })

            $( elements ).delegate( selector, events, data, handler );

        on/off綁定

            $( elements ).on( events, [selector], data, handler );

            $('c1').on('click',function (){...})

<style>
    .d1{
        height:300px;
        width:300px;
        border:1px solid sandybrown;
    }
    .d2{
        height:200px;
        width:200px;
        margin:40px 40px;
        border:1px solid rebeccapurple;
    }
</style>
<div class="d1">
    <div class="d2">
        <span>lala</span>

    </div>
</div>
<script>
    $('.d1').on('click','span',function(){
        alert($(this).text())
    })
</script>


    7、元素高度和寬度:

        image.png

        height/width:獲取/設置元素高度/寬度-內容高、寬

        innerHeight/innerWidth:獲取/設置元素高度/寬度-內容高\寬+padding

        outerHeight/outerWidth:獲取/設置元素高度/寬度-內容高\寬+padding+border

        outerHeight(true)/outerWidth(true):獲取/設置元素高度/寬度-內容高\寬+padding+border+margin

<style>
    #out{
        height:300px;
        width:300px;
        border:10px solid darkred;
        padding:20px;
    }
    #in{
        height:100px;
        width:100px;
        border:10px solid rebeccapurple;
        padding:5px;
        margin-top:30px;
    }
</style>
<div id="out">
    <div id="in">
        <span id="nei">
            lalalalala
        </span>
    </div>
</div>
<script>
    var height_in=$('#in').width();
    t="height:"+height_in+'<br>';
    height_in=$('#in').innerWidth();
    t=t+"height:"+height_in+'<br>';
    height_in=$('#in').outerHeight();
    t=t+"height:"+height_in+'<br>';
    height_in=$('#in').outerHeight(true);
    t=t+"height:"+height_in+'<br>';
    $('#nei').html(t);
</script>

        8、return false阻止事件發生

            以下程序,不跳轉到href這個網址

<div class="d1">
    <div class="d2">
        <a onclick="return doNot()" href="http://www.baidu.com">lala</a>
    </div>
</div>
<script>
    function doNot(){
        alert($('a').text());
        return false;
    }
</script>


        9、jquery擴展

            .extend

            .fn.extend



1、左側彈出菜單,點擊出現子菜單,其它隱藏

    HTML

  <div id='f1'>
    <div id='m1' class='bg'>菜單一</div>
      <ul>
        <li>sub11</li>
        <li>sub12</li>
        <li>sub13</li>
      </ul>
    <div id='m2' class='bg'>菜單二</div>
      <ul>
        <li>sub21</li>
        <li>sub22</li>
        <li>sub23</li>
      </ul>
    <div id='m3' class='bg'>菜單三</div>
      <ul>
        <li>sub31</li>
        <li>sub32</li>
        <li>sub33</li>
      </ul>
  </div>

    jQuery:

  <script>
    $(document).ready(function (){$('.bg').next().hide()});                    //文檔加載完隱藏所有標籤
    $('.bg').click(function(){$(this).next().toggle().siblings('ul').hide()}) //點擊展開,再點隱藏效果,鏈式編程。
  </script>


2、彈出窗口,窗口其它元素不可操作。點叉關閉

    CSS樣式

    .header-menu{
      display:inline-block;
      margin-right:20px;
      height:40px;
    }
    .zhezhao{
      display:none;
      position:fixed;
      left:0;
      top:0;
      right:0;
      bottom:0;
      background-color:gray;
      z-index:8;
      opacity:0.7;
    }
    .regedit{
      display:none;
      width:400px;
      height:600px;
      position:fixed;
      background:white;
      left:50%;
      top:50%;
      margin-left:-200px;
      margin-top:-300px;
      z-index:9;
    }
    .login{
      display:none;
      width:400px;
      height:400px;
      position:fixed;
      background:white;
      left:50%;
      top:50%;
      margin-left:-200px;
      margin-top:-300px;
      z-index:9;
    }
    .divouter{
      width:100%;
      background:gray;
      text-align:right;
    }
    .close_flag{
      padding-right:10px;
      padding-top:10px;
      width:30px;
    }
    .show{
      display:block;
    }


    HTML

  
  
  <!--頭部banner!-->
  <div class='header'>
    <span id='regedit' name='regedit' class='header-menu'>註冊</span>
    <span id='login'  name='login' class='header-menu'>登陸</span>
  </div>
  <!--遮罩!-->
  <div class='zhezhao'></div>
  <!--註冊框-->
  <div class='regedit'>
    <div class='divouter'>
      <span id='hide' name='regedit' class='close_flag'>✖<span>
    </div>
  </div>
  <!--login登陸框!divouter定位X,span樣式-->
  <div class='login'>
    <div class='divouter'>   
      <span id='hide' name='login' class='close_flag'>✖<span>
    </div>
  </div>

    jQuery

    //顯示註冊/登陸框
    $('.header-menu').click(function(){
      $('.zhezhao').addClass('show');
      var sh = $(this).attr('name');        //使用獲取到的屬性值進行二次定位,達到動態效果。
      var s='.'+sh;
      $(s).addClass('show');                               
    })
    //關閉顯示/登陸框
    $('.close_flag').click(function(){
      $('.zhezhao').removeClass('show');
      var hi=$(this).attr('name');
      var h='.'+hi;
      $(h).removeClass('show');
    })

3、鼠標移入和移出背景變色:

    HTML:

  <style>
    .header{
      background-color:#1c97f5;
      height:40px;
      width:100%;
      min-width:960px;
      margin:0 auto;
      line-height:40px;
      text-align:right;
    }
    .header-menu{
      display:inline-block;
      margin-right:20px;
      height:40px;
    }
   </style>
  <div class='header'>
    <span class='header-menu'>註冊</span>
    <span class='header-menu'>登陸</span>
  </div>

    jQuery:

    $('.header-menu').mouseover(function(i,v){$(this).css({'backgroundColor':'#2550aa','color':'white'})})
    $('.header-menu').mouseout(function(i,v){$(this).css({'backgroundColor':'','color':''})})

4、TAB式菜單:

    HTML

  <style>
    .tab_div{
      background:gray;
      height:30px;
      width:100%;
      
    }
    .tab_div span{
      color:white;
      line-height:30px;
      display:inline-block;
      height:30px;
      padding-right:10px;
      padding-left:10px;
    }
    .tab_content{
      display:none;
      position:absolute;
      background:#dde0e3;
      width:100%;
      top:52px;
      bottom:0px;
    }
    .tab_over{
      background-color:#4e5154;
    }
    
 </style>
    <div class='tab_div'><span id='t1'>標籤一</span><span id='t2'>標籤二</span><span id='t3'>標籤三</span>
    </div>
    <div id='tab_content'>
      <div name='t1' class='tab_content'>111111</div>
      <div name='t2' class='tab_content'>2222222</div>
      <div name='t3' class='tab_content'>333333</div>
    </div>

    jQuery

    //tab菜單腳本,實現方法千千萬~這裏沒有選擇Addclass,因爲class有前後定義的毛病~
    
      $("[name='t1']").show()
      $('.tab_div').children().mouseover(function(){
        $(this).addClass('tab_over').siblings().removeClass('tab_over');
        var d=$(this).addClass('tab_over').attr('id');
        var n = "[name='"+d+"']"
        $(n).show().siblings().each(function(){
          $(this).hide()
        })
      });
 
    //方案二:可以刪除子菜單ID,省代碼~更簡潔~

      $(document).ready(function(){
        $(".tab_div").children().mouseover(function(i){
          $(this).addClass('tab_over').siblings().removeClass('tab_over');
          $('.tab_content').eq($(this).index()).show().siblings().hide();
        })
      })

5、點贊動態效果

    html:

<style>
    #zan{
     position: relative;
     width: 30px;
     cursor:pointer;
    }
    .jiayi{
          color:red;
          position:absolute;
        }

</style>

<br><br><br><br><br><br><br><br><br><br>
<div id="zan">贊</div>

    jQuery:

<script src="jquery-1.12.4.js"></script>
<script>
    $(document).ready(function () {
        $('#zan').click(function(){
            var font_size=14;
            var top=0;
            var right=0;
            var opacity=1;
            var ta=document.createElement('span');
                        $(ta).addClass('jiayi');
            $(ta).css('font-size',font_size+'px');
            $(ta).css('top',top+'px');
            $(ta).css('right',right+'px');
            $(ta).css('opacity',opacity);
            $(ta).text('+1');
            $(this).append(ta);

            var inter=setInterval(function(){
                font_size+=1;
                top-=2;
                right-=2;
                opacity-=0.1;
                $(ta).css('font-size',font_size+'px');
                $(ta).css('top',top+'px');
                $(ta).css('right',right+'px');
                $(ta).css('opacity',opacity);
                if (opacity<0){
                    $(ta).remove();
                    clearInterval(inter);
                }
            },20)
        });
    })

</script>

6、註冊框判斷是否爲空,爲空返回並提示:

        本質是用return跳出函數,並給標籤返回一個False。

        HTML

<div class='header'>
  <span id='regedit' name='regedit' class='header-menu'>註冊</span>
  <span id='login'  name='login' class='header-menu'>登陸</span>
</div>
<div class='zhezhao'></div>
  <div class='regedit'>
    <div class='divouter'>
    <span id='hide' name='regedit' class='close_flag'>✖</span>
  </div>
  <div>
      <table >
          <tbody id="reg_tb">
              <tr>
                  <td>用戶名:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>密碼:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>確認密碼:</td>
                  <td><input type="text"/></td>
                  <td>111</td>
              </tr>
              <tr>
                  <td>郵箱:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>電話:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>愛好:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
          </tbody>
      </table>
      <div>
          <input type="button" id='submit' value="提交">
          <input type="button" id='cancel' value="重置">

      </div>
  </div>
</div>
<div class='login'>
  <div class='divouter'>
    <span id='hide' name='login' class='close_flag'>✖</span>
  </div>
</div>

        CSS

.tab_div span{
  color:white;
  line-height:30px;
  display:inline-block;
  height:30px;
  padding-right:10px;
  padding-left:10px;
  background-color:#4e5154;
}
table{
  width:100%
}
.close_flag{
  padding-right:10px;
  padding-top:10px;
  width:30px;
}
.header-menu{
  display:inline-block;
  margin-right:20px;
  height:40px;
}
.zhezhao{
  display:none;
  position:fixed;
  left:0;
  top:0;
  right:0;
  bottom:0;
  background-color:gray;
  z-index:8;
  opacity:0.7;
}
.regedit{
  display:none;
  width:400px;
  height:600px;
  position:fixed;
  background:white;
  left:50%;
  top:50%;
  margin-left:-200px;
  margin-top:-300px;
  z-index:9;

}
.login{
    display:none;
    width:400px;
    height:400px;
    position:fixed;
    background:white;
    left:50%;
    top:50%;
    margin-left:-200px;
    margin-top:-300px;
    z-index:9;
}
.divouter{
  width:100%;
  background:gray;
  text-align:right;
}
.close_flag{
  padding-right:10px;
  padding-top:10px;
  width:30px;
}

        jQuery

<script>
    ($('#submit').click(function(){
        var flag=true;
        var dic=[];
        $('#reg_tb').children().each(function(){
            var input_box=$(this).children().eq(1).children().eq(0).val();
            console.log(input_box);
            if (input_box.length<=0) {
                flag = false;
                $(this).children().eq(2).html('<span style="color:red">*必填項</span>');
                return flag;
            }else{
                dic.push(input_box);
                $(this).children().eq(2).html('');
            }
        });
        if (flag){
            console.log(dic);
        }
        return flag;
    }));
    
    
    \\控制遮罩
$(document).ready(function (){$('.bg').next().hide()});                    //文檔加載完隱藏所有標籤
$('.bg').click(function(){$(this).next().toggle().siblings('ul').hide()}) //點擊展開,再點隱藏效果,鏈式編程。
$('.header-menu').mouseover(function(i,v){$(this).css({'backgroundColor':'#2550aa','color':'white'})})
$('.header-menu').mouseout(function(i,v){$(this).css({'backgroundColor':'','color':''})})
//顯示註冊/登陸框
$('.header-menu').click(function(){
  $('.zhezhao').addClass('show');
  var sh = $(this).attr('name');
  var s='.'+sh;
  $(s).addClass('show');
})
//關閉顯示/登陸框
$('.close_flag').click(function(){
  $('.zhezhao').removeClass('show');
  var hi=$(this).attr('name');
  var h='.'+hi;
  $(h).removeClass('show');
})



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