玩转jquery

一 jquery简介

中文文档:http://jquery.cuishifeng.cn/

 

1 jquery是什么  

  • jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team
  • jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE,写更少的代码,做更多的事情。
  • 它是轻量级的js(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器 (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)。
  • jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documentsevents、实现动画效果,并且方便地为网站提供AJAX交互。
  • jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。
  • jQuery能够使用户的html页保持代码和html内容分离,也就是说,不用再在html里面插入一堆js来调用命令了,只需定义id即可。

 

2 什么是jQuery对象?

  • jQuery 对象就是通过jQuery包装DOM对象后产生的对象。
  • jQuery 对象是 jQuery 独有的如果一个对象是 jQuery 对象那么它就可以使用 jQuery 里的方法: $(“#test”).html();

      比如: 

      $("#test").html()   意思是指:获取IDtest的元素内的html代码。其中html()jQuery里的方法 

      这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML; 

虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错

约定:如果获取的是 jQuery 对象那么要在变量前面加上$. 

var $variable = jQuery 对象

var variable = DOM 对象

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

 

二 寻找元素(重要的选择器和筛选器)  

2.1   选择器

    2.1.1 基本选择器      $("*")  // 全部标签  $("#id") // 根据ID值寻找   $(".class")  // 根据class名字寻找  $("element") // 根据元素标签名字寻找  $(".class,p,div")  // 逗号表示并列关系

    2.1.2层级选择器       $(".outer div") // 后代选择器   $(".outer>div") // 子代选择器   $(".outer+div") // 毗邻选择器,必须紧挨着下一个标签  $(".outer~div")  //匹配 outer 元素之后的所有 div 元素

    2.1.3 基本筛选器      $("li:first") // 获取第一个元素  $("li:eq(2)") //匹配一个给定索引值的元素   $("li:even") // 匹配偶数元素 $("li:gt(1)") // 匹配大于索引值为1的元素

    2.1.4 属性选择器      $('[id="div1"]')   $('["alex="sb"][id]')     // 匹配给定的属性是某个特定值的元素

    2.1.5 表单选择器      $("[type='text']")----->$(":text")                    注意只适用于input标签    // input标签可以使用简写的方式表达属性选择器

                                 $("input:checked")

 

2.2 筛选器

     2.2.1  过滤筛选器

                                     $("li").eq(2)   // 获取索引为2的li元素

                 $("li").first()  // 获取第一个元素

          $("ul li").hasclass("test")   //ul 下的li 元素集合中是否有class属性是"test"的,返回一个布尔值

     2.2.2  查找筛选器

                                $("div").children(".test")     // parents()将查找所有祖辈元素,而children()只考虑子元素而不考虑所有后代元素。    $("div").find(".test")  // 所有的后代元素全部找出来

                                $(".test").next()    $(".test").nextAll()   $(".test").nextUntil()   // next 相邻的下一个元素,nextAll 下面的所有元素,nextUntil 

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

                                $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 

                                $("div").siblings()

 

例子:

<div class="div7">hello div7</div>
<div class="div8">hello div8</div>

<div class="div1"> hello div1
    <div class="div2"> hello div2
        <div class="div3"> hello div3</div>
    </div>
</div>
<div class="div4">hello div4</div>
<div class="div5">hello div5</div>
<div class="div6">hello div6</div>





$(".div1").next()
    // div4
$(".div1").nextAll()
  // div4,5,6
$(".div1").nextUntil(".div6")
   //不包含.div6元素   ,div4,5


$(".div1").prev()
      // div8
$(".div1").prevAll()
   // div8,div7
$(".div1").prevUntil(".div7")
   //不包含.div6元素


$(".div3").parent()   // div2

$(".div1").parents()
  //[div.div2, div.div1, body, html, prevObject: jQuery.fn.init(1)]


$(".div1").siblinegs() //[div.div7, div.div8, div.div4, div.div5, div.div6, script, prevObject: jQuery.fn.init(1)]

实例 左侧菜单 

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

    <script src="js/jquery-2.2.3.js"></script>
    <script>
          function show(self){
//              console.log($(self).text())
              $(self).next().removeClass("hide")
              $(self).parent().siblings().children(".con").addClass("hide")

          }
    </script>
    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              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>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>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>

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

</div>

</body>
</html>
View Code

实例 tab切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
           function tab(self){
               var index=$(self).attr("xxx")
               $("#"+index).removeClass("hide").siblings().addClass("hide")
               $(self).addClass("current").siblings().removeClass("current")

           }
    </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;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </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>
</html>
View Code

 三   操作元素(属性 CSS 和 文档处理)  

3.1 属性操作

      $("p").text()  // 获取标签元素内容,浏览器不解析    $("p").html()   // 获取标签元素内容,浏览器解析  $(":checkbox").val()  // 获取标签元素的value 

      $(".test").attr("alex")  // 获取 class='test'标签元素的 “alex”属性的值,属于自定义属性  $(".test").attr("alex","sb")  // 修改 class='test'标签元素的 “alex”属性的值 为 'sb'

      $(".test").attr("checked","checked")  $(":checkbox").removeAttr("checked") // 删除checked属性

      $(".test").prop("checked",true)  // 修改checked的属性值为true  ,自带的属性

      $(".test").addClass("hide")   // 添加css 属性

总结: 自定义属性使用att,removeAtt

             自带的属性使用prop,removeProp

             添加class属性使用addClass(), 移除class属性使用removeClass()

 

实例 编辑框正反选

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

             function selectall(){

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

                 $("table :checkbox").prop("checked",false)
             }

             function reverse(){


//                 var idlist=$("table :checkbox")
//                 for(var i=0;i<idlist.length;i++){
//                     var element=idlist[i];
//
//                     var ischecked=$(element).prop("checked")
//                     if (ischecked){
//                         $(element).prop("checked",false)
//                     }
//                     else {
//                         $(element).prop("checked",true)
//                     }
//
//                 }



                 $("table :checkbox").each(function(){    // 循环 $("table :checkbox")
                     if ($(this).prop("checked")){     // this 表示获取的当前标签元素对象比如,你点击的标签元素对象
                         $(this).prop("checked",false)
                     }
                     else {
                         $(this).prop("checked",true)
                     }

                 });



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

             }

    </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>
</html>
View Code

实例 模态对话框

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>批量编辑</title>
        <!--<link rel="stylesheet" href="css/mycss.css" />-->
        <style>
            *{
    margin: 0;
    padding: 0;
}
body {
  font-family: 'Open Sans', sans-serif;
  font-weight: 300;
  line-height: 1.42em;
  color:rebeccapurple;
  background-color:goldenrod;
}

h1 {
  font-size:3em;
  font-weight: 300;
  line-height:1em;
  text-align: center;
  color: #4DC3FA;
}
.blue {
    color: #185875;
}
.yellow {
    color: #FFF842;
    }

/*!*弹出层罩子*!*/
#full {
    background-color:gray;
    left:0;
    opacity:0.7;
    position:absolute;
    top:0;
    filter:alpha(opacity=30);
}

.modified {
    background-color: #1F2739;
    border:3px solid whitesmoke;
    height:400px;
    left:50%;
    margin:-200px 0 0 -200px;
    padding:1px;
    position:fixed;
    /*position:absolute;*/
    top:50%;
    width:400px;
    display:none;
}
li {
    list-style: none;
    margin: 20px 0 0 50px;
    color: #FB667A;
}
input[type="text"] {
  padding: 10px;
  border: solid 1px #dcdcdc;
  /*transition: box-shadow 3s, border 3s;*/

}

.iputbutton {
    margin: 60px 0 0 50px;
    color: whitesmoke;
    background-color: #FB667A;
    height: 30px;
    width: 100px;
    border: 1px dashed;

}




.container th h1 {
    font-weight: bold;
    font-size: 1em;
      text-align: left;
      color: #185875;
}

.container td {
    font-weight: normal;
    font-size: 1em;
}

.container {

    width: 80%;
    margin: 0 auto;

}

.container td, .container th {
    padding-bottom: 2%;
    padding-top: 2%;
      padding-left:2%;
}

/*单数行*/
.container tr:first-child {
    background-color: red;
}

/*偶数行*/
.container tr:not(first-child){
      background-color: cyan;
}

.container th {
    background-color: #1F2739;
}

.container td:last-child {
    color: #FB667A;
}
/*鼠标进过行*/
.container tr:hover {
   background-color: #464A52;
}
/*鼠标进过列*/
.container td:hover {
  background-color: #FB667A;
  color: #403E10;
  font-weight: bold;
  transform: translate3d(5px, -5px, 0);
}





        </style>
        <script src="jquery-3.1.1.js"></script>
        <script>
            //点击【编辑】显示

$(function () {


    $("table[name=host] tr:gt(0) td:last-child").click(function (event) {

        alert("234");
//        $("#full").css({height:"100%",width:"100%"});

        $(".modified").data('current-edit-obj', $(this));

        $(".modified,#full").show();

        var hostname = $(this).siblings("td[name=hostname]").text();
        $(".modified #hostname").val(hostname);
        var ip = $(this).siblings("td[name=ip]").text();
        $(".modified #ip").val(ip);
        var port = $(this).siblings("td[name=port]").text();
        $(".modified #port").val(port);
    });
    //取消编辑
    $(".modified #cancel").bind("click", function () {
        $(".modified,#full").hide();
    });

//    确定修改
    $(".modified #ok").bind("click", function (event) {
        var check_status = true;
        var ths = $(".modified").data('current-edit-obj');
        var hostname = $(".modified #hostname").val().trim();
        var ip = $(".modified #ip").val().trim();
        var port = $(".modified #port").val().trim();
        var port = parseInt(port);
        console.log(port);
        //        端口为空设置为22
        if (isNaN(port)) {
            alert("您没有设置正常的SSH端口号,将采用默认22号端口");
            var port = 22;
        }else if ( port > 65535) {
        //            如果端口不是一个数字 或者端口大于65535
            var check_status = false;
            $(".modified #port").css("border-color","red");
            alert("端口号超过范围!")
        };
        // 主机和ip不能是空
        if ( hostname == ""){
            var check_status = false;
            $(".modified #hostname").css("border-color","red");
        }else if (ip == "") {
            var check_status = false;
            $(".modified #ip").css("border-color","red");
        };
        if (check_status == false){
            return false;
        }else{
            //$(this).css("height","60px")   为什么不用$(this),而用$()
            $(ths).siblings("td[name=hostname]").text(hostname);
            $(ths).siblings("td[name=ip]").text(ip);
            $(ths).siblings("td[name=port]").text(port);
            $(".modified,#full").hide();
        };

    });

});

        </script>
    </head>
    <body>
        <h1>
            <span class="blue">&lt;</span>Homework1<span class="blue">&gt;</span> <span class="yellow">HostList</span>
        </h1>
        <div id="full">
            <div class="modified">
                <li>主机名:<input id="hostname" type="text" value="" />*</li>
                <li>ip地址:<input id="ip" type="text" value="" />*</li>
                <li>端口号:<input id="port" type="text" value="" />[0-65535]</li>
                    <div id="useraction">
                     <input class="iputbutton" type="button" name="确定" id="ok" value="确定"/>
                    <input class="iputbutton" type="button" name="取消" id="cancel" value="取消"/>
                    </div>
            </div>
        </div>
        <table class="container" name="host">
            <tr>
                <th><h1>主机名</h1></th>
                <th><h1>IP地址</h1></th>
                <th><h1>端口</h1></th>
                <th><h1>操作</h1></th>

            </tr>
            <tr>
                <td name="hostname">web01</td>
                <td name="ip">192.168.2.1</td>
                <td name="port">22</td>
                <td>编辑 </td>
            </tr>
            <tr>
                <td name="hostname">web02</td>
                <td name="ip">192.168.2.2</td>
                <td name="port">223</td>
                <td>编辑 </td>
            </tr>
            <tr>
                <td name="hostname">web03</td>
                <td name="ip">192.168.2.3</td>
                <td name="port">232</td>
                <td>编辑 </td>
            </tr>
            <tr>
                <td name="hostname">web04</td>
                <td name="ip">192.168.2.4</td>
                <td name="port">232</td>
                <td>编辑 </td>
            </tr>
        </table>


    </body>
</html>
</html>
这里例子有点给力

 

3.2 CSS操作

        3.2.1(样式)   css("{color:'red',backgroud:'blue'}") 

        3.2.2(位置)   offset()  //元素距离body的距离    position()  scrollTop() //获取匹配元素相对  【滚动条顶部】的偏移。scrollLeft()    

        3.2.3(尺寸)   height()  width()  

1、回顾普通布局
2、新布局
      - overflow:auto:
           上,左菜单固定
      -3、滚动菜单示例:
    新布局(无)
    a. onscroll事件
    b. $(..).scrollTop()   $(..).scrollTop(10) =>$(..).scrollLeft(10)

    c. 如何获取某个标签距离顶部高度
        $(..).offset()        获取当前标签距离文档顶部高度
        
        $(..).height()        永远获取自己的高度;             获取当前标签自己的高度
        $(..).innerHeight()   永远获取自己高度+padding;        获取第一个匹配元素内部区域高度(包括补白、不包括边框)。
        $(..).outerHeight()   
                              参数一:false:
                                永远获取自己高度+padding+border; 获取第一个匹配元素外部高度(默认包括补白和边框)设置为 true 时,计算边距在内。
                              参数二:true
                                永远获取自己高度+padding+border+margin;

 

例子:

// 取得第一个段落的color样式属性的值。
$("p").css("color");

// 将所有段落的字体颜色设为红色并且背景为蓝色。
$("p").css({ "color": "#ff0011", "background": "blue" });

// 将所有段落字体设为红色
$("p").css("color","red");

// 逐渐增加div的大小
$("div").click(function() {
    $(this).css({
      width: function(index, value) {
        return parseFloat(value) * 1.2;
      }, 
      height: function(index, value) {
        return parseFloat(value) * 1.2;
      }
    });
  });
CSS例子

 

posted @ 2017-09-04 16:09  wanstack  阅读(156)  评论(0)    收藏  举报