【jQuery】

一、jQuery的定义

jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(或JavaScript框架)。jQuery设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。

jQuery的核心特性可以总结为:具有独特的链式语法和短小清晰的多功能接口;具有高效灵活的css选择器,并且可对CSS选择器进行扩展;拥有便捷的插件扩展机制和丰富的插件。jQuery兼容各种主流浏览器,如IE 6.0+、FF 1.5+、Safari 2.0+、Opera 9.0+等。

 

特点

  • 快速获取文档元素
jQuery的选择机制构建于Css的选择器,它提供了快速查询DOM文档中元素的能力,而且大大强化了JavaScript中获取页面元素的方式。
  • 提供漂亮的页面动态效果
jQuery中内置了一系列的动画效果,可以开发出非常漂亮的网页,许多网站都使用jQuery的内置的效果,比如淡入淡出、元素移除等动态特效。
  • 创建AJAX无刷新网页
AJAX是异步的JavaScript和ML的简称,可以开发出非常灵敏无刷新的网页,特别是开发服务器端网页时,比如PHP网站,需要往返地与服务器通信,如果不使用AJAX,每次数据更新不得不重新刷新网页,而使用AJAX特效后,可以对页面进行局部刷新,提供动态的效果。
  • 提供对JavaScript语言的增强
jQuery提供了对基本JavaScript结构的增强,比如元素迭代和数组处理等操作。
  • 增强的事件处理
jQuery提供了各种页面事件,它可以避免程序员在HTML中添加太事件处理代码,最重要的是,它的事件处理器消除了各种浏览器兼容性问题。
  • 更改网页内容
jQuery可以修改网页中的内容,比如更改网页的文本、插入或者翻转网页图像,jQuery简化了原本使用JavaScript代码需要处理的方式。
 

二、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

 

参考文档:http://jquery.cuishifeng.cn/

 

三、jQuery的选择器及筛选器

1、选择器

  • 基本选择器

$("*")   #通用选择器
$("#id")  #id选择器
$(".class")  #类选择器
$("p")  #通用选择器
$(".class,p,div")
  • 层级选择器  

$(".outer div")  #后代元素选择器,匹配所有属于outer元素后代的div元素
$(".outer>div")  #子元素选择器,匹配所有outer元素的子元素div 
$(".outer+div")  #毗邻元素选择器,匹配所有紧随outer元素之后的同级元素div 
$(".outer~div")  #普通兄弟选择器
  • 表单选择器

$(":input")                  选择所有的表单输入元素,包括input, textarea, select 和 button
$(":text")                     选择所有的text input元素
$(":password")           选择所有的password input元素
$(":radio")                   选择所有的radio input元素
$(":checkbox")            选择所有的checkbox input元素
$(":submit")               选择所有的submit input元素
$(":image")                 选择所有的image input元素
$(":reset")                   选择所有的reset input元素
$(":button")                选择所有的button input元素
$(":file")                     选择所有的file input元素
$(":hidden")               选择所有类型为hidden的input元素或表单的隐藏域

 

2、筛选器

  • 基本筛选器

  $("tr:first")               选择所有tr元素的第一个

  $("tr:last")                选择所有tr元素的最后一个

$("tr:even")               选择所有的tr元素的第0,2,4... ...个元素(注意:因为所选择的多个元素时为数组,所以序号是从0开始) 
$("tr:odd")                选择所有的tr元素的第1,3,5... ...个元素
$("td:eq(2)")             选择所有的td元素中序号为2的那个td元素
$("td:gt(4)")             选择td元素中序号大于4的所有td元素
$("td:ll(4)")              选择td元素中序号小于4的所有的td元素

 

  • 属性筛选器

$("div[id]")                   选择所有含有id属性的div元素 
$("input[name='newsletter']")    选择所有的name属性等于'newsletter'的input元素
$("input[name!='newsletter']")  选择所有的name属性不等于'newsletter'的input元素 
$("input[name^='news']")         选择所有的name属性以'news'开头的input元素
$("input[name$='news']")         选择所有的name属性以'news'结尾的input元素
$("input[name*='man']")          选择所有的name属性包含'news'的input元素
$("input[id][name$='man']")    可以使用多个属性进行联合选择,该选择器是得到所有的含有id属性并且那么属性以man结尾的元素

 

  •  内容筛选器
$("div:contains('John')") 选择所有div中含有John文本的元素 
$("td:empty")           选择所有的为空(也不包括文本节点)的td元素的数组 
$("div:has(p)")        选择所有含有p标签的div元素 
$("td:parent")          选择所有的以td为父节点的元素数组 

 

  • 可视化筛选器
$("div:hidden")        选择所有的被hidden的div元素 
$("div:visible")        选择所有的可视化的div元素 

 

  • 表单筛选器

$(":enabled")             选择所有的可操作的表单元素 
$(":disabled")            选择所有的不可操作的表单元素 
$(":checked")            选择所有的被checked的表单元素 
$("select option:selected") 选择所有的select 的子元素中被selected的元素 

 

  • 查找筛选器
 查找子标签:         
$("div").children(".test") #返回匹配元素集合中每个元素的所有子元素仅儿子辈
           
$("div").find(".test")     #返回匹配元素集合中每个元素的后代 向下查找兄弟标签:
$(
".test").next() #紧挨着$('')的一个元素 
$(".test").nextAll() #在$('')以后的所有的同辈元素 
$(
".test").nextUntil() #until有直到。。。之前的意思,所以他表示$('')以后的所有的同辈元素,不过要在nextUntil参数之前,不包括匹配的元素本身 向上查找兄弟标签: $("div").prev() $("div").prevAll() $("div").prevUntil()
查找所有兄弟标签: $(
"div").siblings() 查找父标签: $(".test").parent() $(".test").parents() $(".test").parentUntil()

 

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

    <script src="jquery-3.2.1.min.js"></script>
</head>
<body>

<p>p123</p>
<p class="item">p123</p>
<p class="item">p123</p>
<p id="p1">p123</p>

<div class="outer">
    <div class="inner">
        <div id="d1">DIV</div>
        <p>p1</p>
    </div>
    <p>p2</p>
</div>


<div class="c1">
    <div class="c2">
        <ul class="num">
            <li>111</li>
            <li>222</li>
            <li>333</li>
            <li class="l4">444</li>
            <li>555</li>
        </ul>

    </div>
</div>
<div hx="1000">hx is egg!</div>
<div hx="2000">hx is egg!</div>


<input type="text">
<input type="checkbox">

<script>
    //============================== 直接查找标签
    // 基本选择器
    // ---标签的选择器
    // $("p").css("color","red")  ;                 //  [ele1,ele2]
    // --- class  选择器
    //$(".item").css("color","red");
    // --- id  选择器
   // $("#p1").css("color","red")

    // 层级选择器
    //$(".outer p").css("color","red");
    //$(".outer>p").css("color","red");

    // 基本筛选器 :
    // $(".num li:first").css("color","red");
    // $(".num li:last").css("color","red");
    //$(".num li:eq(2)").css("color","red");
   // $(".num li:gt(3)").css("color","red");
    //$(".num li:odd").css("color","red");
    //$(".num li:even").css("color","red");

    // 属性选择器
    // $("[egon=1000]").css("color","red");
    // 表单选择器: 针对表单标签
    //$("[type='text']").css("border","1px solid red");

    // $(":text").css("border","1px solid red");
    // $(":checkbox").css("border","1px solid red");

    //  筛选器
    // var num=2;
    //
    // //$(".num li:eq(num)").css("color","red");
    // $(".num li").eq(num).css("color","red");

    // ======================================导航查找标签
   // 找兄弟
   // $(".num li").eq(1).next().css("color","red"); // 找下一个兄弟标签
   // $(".num li").eq(1).nextAll().css("color","red") ; // 找下一个兄弟标签
   // $(".num li").eq(0).nextUntil(".l4").css("color","red") ; // 找下一个兄弟标签

     // 查找所有的兄弟标签
     // $(".num li").eq(1).siblings().css("color","red")

     //  找儿子
    //$(".outer").children("p").css("color","red")
    //$(".outer").find("p").css("color","red")

     // 找父亲
    // $(".l4").parent().css("color","red")
    // $(".l4").parents().css("color","red")
    // $(".l4").parentsUntil(".c1").css("color","red")



</script>
</body>
</html>
示例

 

四、jQuery的操作元素

1、事件

  • 事件绑定

语法: 标签对象.事件(函数)

$("p").click(function(){})

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


<p>111</p>
<p id="p1">222</p>
<p>333</p>



<script src="jquery-3.2.1.min.js"></script>
<script>
    //   $().事件方法名(function(){       })
    $("p").click(function () {
        //console.log(this)      // this 指的是当前事件触发的标签
        // console.log($(this))
        //alert(this);   //   Dom(标签)对象-------->  $(dom)

        alert($(this).html())
     })

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

 

2、文本操作

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

<div>
    <p>DIV</p>
</div>
<button>click</button>
<p>PPP</p>

<script src="jquery-3.2.1.min.js"></script>
<script>

    //  文本取值

    console.log($("div").text());  //  不识别标签,只取文本
    console.log($("div").html());   // 识别标签

     // 文本赋值

    $("button").click(function () {
        // 操作p标签
        //$("div p").text("hello");
       // $("div p").html("hello")


        $("div").text("<a href=''>click</a>");
        //$("div").html("<a href=''>click</a>");



    })
</script>
</body>
</html>

 

3、class操作

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

    <style>
        .c1{
            color: rebeccapurple;
        }
        .c2{
            background-color: gray;
        }
        .c3{
            font-size: 32px;
        }
    </style>
</head>
<body>


<script src="jquery-3.2.1.min.js"></script>
<div class="c1 c2">DIV</div>

<script>
    /*
    $("div").addClass("c3")
    r.fn.init [div.c1.c2.c3, prevObject: r.fn.init(1)]
    $("div").addClass("c3")
    r.fn.init [div.c1.c2.c3, prevObject: r.fn.init(1)]
    $("div").removeClass("c1")
    r.fn.init [div.c2.c3, prevObject: r.fn.init(1)]
    $("div").removeClass("c2")
    r.fn.init [div.c3, prevObject: r.fn.init(1)]
    $("div").removeClass("c2")
    r.fn.init [div.c3, prevObject: r.fn.init(1)]
    $("div").removeClass("c1")
    r.fn.init [div.c3, prevObject: r.fn.init(1)]
    $("div").removeClass("c3")
    r.fn.init [div, prevObject: r.fn.init(1)]


     */

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

 

 

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .left_menu{
            width: 20%;
            height: 600px;
            background-color: darkgrey;
            float: left;
        }

        .content{
            width: 80%;
            height: 600px;
            background-color: cadetblue;
            float: left;
        }
        .hide{
            display: none;
        }

        .item{
            margin-top: 20px;
        }
    </style>
</head>
<body>

<div>
    <div class="left_menu">
          <div class="item">
            <div class="title c1">菜单一</div>
            <div class="con">
                <p>111</p>
                <p>111</p>
                <p>111</p>
            </div>
        </div>
          <div class="item">
            <div class="title c2">菜单二</div>
            <div class="con hide">
                <p>222</p>
                <p>222</p>
                <p>222</p>
            </div>
        </div>
          <div class="item">
            <div class="title c3">菜单三</div>
            <div class="con hide">
                <p>333</p>
                <p>333</p>
                <p>333</p>

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

<script src="jquery-3.2.1.min.js"></script>

<script>
    $(".title").click(function () {
        // console.log($(this));
        // 第一: 当前触发事件的标签的兄弟标签
        //$(this).next().removeClass("hide");

        //$(this).parent().siblings().children(".con").addClass("hide")

        // 支持链式操作

        $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");
    })
</script>
</body>
</html>
左侧菜单

 

 4、事件委派

$("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。

     // li的弹出文本事件
    // $("ul li").click(function () {
    //     alert($(this).html())
    // });


     // 事件委派

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

可实现新增即刷新。

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


<ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
</ul>
<button>Add</button>
<script src="jquery-3.1.1.js"></script>

<script>
     // li的弹出文本事件
//     $("ul li").click(function () {
//         alert($(this).html())
//     });

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

     // 事件委派

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

    // button的追加子元素吧事件
    $("button").click(function () {

        $("ul").append("<li>444</li>")
    })
</script>
</body>
</html>
事例

 

 

5、属性操作

--------------------------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"})

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.2.1.min.js"></script>
    <style>
        #i3{
            color: green;
        }
    </style>
</head>
<body>


<p class="c1 c2" id="i1" egon="9000">this is P</p>
<p id="i3">this is P</p>

<input type="checkbox" >

<script>
    // 取某一个属性的值
    $(".c1").attr("id");
    $(".c1").attr("egon");

    // 赋值操作
     $(".c1").attr("id","i2");
     $(".c1").attr("egon",9999);
   // css的样式操作
   $("#i3").click(function () {
       // $(this).css("color","red");
       $(this).css({"color":"red","fontSize":"32px"})
   })

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

 

6.each循环 

 方式一:

格式:$.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())
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<div class="outer">
    <p>111</p>
    <p>222</p>
    <p>333</p>
</div>


   <script src="jquery-3.2.1.min.js"></script>
    <script>

        // jquery两种循环方式
        // 方式1:$.each(循环对象,function(){
        //     console.log("OK")
        // });

        // var arr=[111,222,333];
        //
        // var info={"name":"egon","age":9000};
        //
        // $.each(info,function (i,j) {
        //    console.log(i); // 下标
        //    console.log(j); // 下标 对应的值
        // })

        // 方式2:
        $(".outer p").each(function () {
            console.log($(this).html())  // $(this)指的是每一次循环的对象
        })




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

 

7、表格正反选

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

<button class="select_all">全选</button>
<button class="cancel">取消</button>
<button class="reverse">反选</button>
<hr>
<table border="1">
    <tr>
        <td><input type="checkbox"></td>
        <td>张三</td>
        <td>23</td>
        <td>s5</td>
    </tr>
        <tr>
        <td><input type="checkbox"></td>
        <td>李四</td>
        <td>23</td>
        <td>s5</td>
    </tr>
        <tr>
        <td><input type="checkbox"></td>
        <td>王五</td>
        <td>23</td>
        <td>s8</td>
    </tr>
</table>


<script src="jquery-3.2.1.min.js"></script>

<script>
    
    // 全选事件
    $(".select_all").click(function () {
        //  方式1:
        // $(":checkbox").each(function () {
        //     $(this).prop("checked",true)
        // })

        // 方式2
        $(":checkbox").prop("checked",true)

    });

    // 取消事件
    $(".cancel").click(function () {

         $(":checkbox").prop("checked",false)
    });
    
    // 反选事件
    
    $(".reverse").click(function () {
        $(":checkbox").each(function () {

           // if($(this).prop("checked")){
           //     $(this).prop("checked",false)
           // }
           // else {
           //      $(this).prop("checked",true)
           // }

            // 方式2:
            $(this).prop("checked",!$(this).prop("checked"))

        })
    })
</script>
</body>
</html>

 

8、节点操作 

//创建一个标签对象
    $("<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]])

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .outer{
            width: 400px;
            height: 300px;
            background-color: darkgrey;
        }
    </style>
    <script src="jquery-3.2.1.min.js"></script>
</head>
<body>

<div class="outer">

    <h4>hello world</h4>
    <p>123</p>
    <p>456</p>
    <p>789</p>

</div>

<hr>
<button class="add">Add</button>
<button class="del">删除</button>
<button class="set">替换</button>

<script>

     // 添加节点操作
    $(".add").click(function () {
        // 创建一个img标签对象

        var $img=$("<img>");    //   <img>
        $img.attr("src","egg.jpg");

        console.log($img[0]);

        // 添加到指定节点中: $(父标签).append(添加的子标签)

       // $(".outer").append($img);
       // $img.appendTo(".outer")
        $(".outer").after($img)

    });

    // 删除节点操作
    $(".del").click(function () {
        $(".outer").remove()
        //$(".outer").empty()     // empty 清空
    });

    // 替换节点
    $(".set").click(function () {
        var $img=$("<img>");    //   <img>
        $img.attr("src","egg.jpg");
        $(".outer p").eq(1).replaceWith($img)

    });

    // 拷贝节点
    var $copy=$(".outer").clone();
    console.log($copy[0])


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

 

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


<div class="style_box">
    <div class="item">
        <button class="add">+</button><input type="text">
    </div>

</div>

<script>
    //  添加事件
    $(".item .add").click(function () {

        var $clone=$(this).parent().clone();
        $clone.children(".add").html("-").attr("class","del");

        $(".style_box").append($clone);

    });

    // 删除事件(事件委派)

    $(".style_box").on("click",".del",function () {

        console.log($(this));

        $(this).parent().remove()
    })
</script>
</body>
</html>
实例2

 

9、动画效果

  • 显示和隐藏

$(".c1").show(1000);  #显示,元素在1秒钟(1000毫秒)内显示出来

$(".c1").hide(1000);#隐藏

$(".c1").toggle(1000)#切换

 

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


</head>
<body>

<div class="c1">DIV</div>
<button class="xianshi">显示</button>
<button class="yincang">隐藏</button>
<button class="qiehuan">切换</button>
<script src="jquery-3.2.1.min.js"></script>

<script>
    $(".xianshi").click(function () {
        // $(".c1").removeClass("hide")
       $(".c1").show(1000);

    });

     $(".yincang").click(function () {

         $(".c1").hide(1000);
    });

       $(".qiehuan").click(function () {

         $(".c1").toggle(1000)
    });
</script>
</body>
</html>
显示,隐藏,切换

 

  • 上下滑动隐藏和显示

$(".con").slideDown(2000)

$(".con").slideUp(2000)

$(".con").slideToggle(1000)

 

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


</head>
<body>

<div class="c1">
    <div class="title">菜单1</div>
    <div class="con">
        <p>111</p>
        <p>111</p>
        <p>111</p>
    </div>
</div>
<hr>
<button class="xianshi">显示</button>
<button class="yincang">隐藏</button>
<button class="qiehuan">切换</button>
<script src="jquery-3.2.1.min.js"></script>

<script>
    $(".xianshi").click(function () {

       $(".con").slideDown(2000)

    });

     $(".yincang").click(function () {
       $(".con").slideUp(2000)
    });

      $(".qiehuan").click(function () {
       $(".con").slideToggle(1000)
    });
</script>
</body>
</html>
滑动

 

  • 淡入和淡出

$(".c1").fadeIn(2000)

$(".c1").fadeOut(2000)

$(".c1").fadeToggle(2000)
 $(".c1").fadeTo(2000,0.2) #淡出到透明度0.2

 

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

    <style>
        .c1{
            width: 200px;
            height: 200px;
            background-color: green;
        }
    </style>
</head>
<body>

<div class="c1"></div>

<hr>
<button class="xianshi">显示</button>
<button class="yincang">隐藏</button>
<button class="qiehuan">切换</button>
<script src="jquery-3.2.1.min.js"></script>

<script>
    $(".xianshi").click(function () {

       $(".c1").fadeIn(2000)

    });

     $(".yincang").click(function () {
       $(".c1").fadeOut(2000)
    });

      $(".qiehuan").click(function () {
      $(".c1").fadeToggle(2000)
      // $(".c1").fadeTo(2000,0.2)
    });
</script>
</body>
</html>
淡入淡出

 

10、css操作

  • 位置操作

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

#获取匹配元素在当前视口的相对偏移。返回的对象包含两个整型属性:top 和 left,以像素计。此方法只对可见元素有效。


$("").position()

 

#获取匹配元素相对父元素的偏移。

返回的对象包含两个整型属性:top 和 left。为精确计算结果,请在补白、边框和填充属性上使用像素单位。此方法只对可见元素有效。

 

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

 

#

获取匹配元素相对滚动条顶部的偏移。

此方法对可见和隐藏元素均有效。

 

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

#

获取匹配元素相对滚动条左侧的偏移。

此方法对可见和隐藏元素均有效。

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
        }
        .c1,.c2{
            width: 200px;
            height: 200px;
        }
        .c1{
            background-color: darkgrey;
        }
        .c2{
            background-color: cadetblue;
        }
        .c3{
            position: relative;
        }

    </style>
</head>
<body>

<div class="c1"></div>
<div class="c3"><div class="c2"></div></div>

<script src="jquery-3.2.1.min.js"></script>
<script>
    // 获取偏移量
    // console.log($(".c1").offset().left);
    // console.log($(".c1").offset().top);
    console.log($(".c2").offset().left);
    console.log($(".c2").offset().top);


    console.log($(".c2").position().left);
    console.log($(".c2").position().top);   // 不可以设置

    // 设置偏移量
    //$(".c2").offset({top:200,left:200})

</script>
</body>
</html>
偏移量事例

 

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


    <style>
        *{
            margin: 0;
        }
        .c1{
            width: 100%;
            height: 2000px;
            background-color: darkgrey;

        }

        .returnTop{
            width: 100px;
            height: 46px;
            background-color: darkcyan;
            color: white;
            text-align: center;
            line-height: 46px;
            position: fixed;
            bottom: 20px;
            right: 20px;
                }


        .hide{
            display: none;
        }
    </style>
</head>
<body>

<div class="c1">
    <h1>yuan</h1>
</div>

<div class="returnTop hide">返回顶部</div>


<script src="jquery-3.2.1.min.js"></script>
<script>
    // 返回顶部事件
    $(".returnTop").click(function () {

      $(window).scrollTop(0)

    });

    // 监听滚动条的位置

    $(window).scroll(function () {

       console.log($(window).scrollTop());
        var $current_position=$(window).scrollTop()

        if($current_position>200){

           $(".returnTop").show()
        }
        else {
             $(".returnTop").hide()
        }
    })





</script>
</body>
</html>
返回顶部

 

11.event

件方法会触发匹配元素的事件,或将函数绑定到所有匹配元素的某个事件。

触发实例:

$("button#demo").click()

上面的例子将触发 id="demo" 的 button 元素的 click 事件。

绑定实例:

$("button#demo").click(function(){$("img").hide()})

上面的例子会在点击 id="demo" 的按钮时隐藏所有图像。

方法    描述
bind()    向匹配元素附加一个或更多事件处理器
blur()    触发、或将函数绑定到指定元素的 blur 事件
change()    触发、或将函数绑定到指定元素的 change 事件
click()    触发、或将函数绑定到指定元素的 click 事件
dblclick()    触发、或将函数绑定到指定元素的 double click 事件
delegate()    向匹配元素的当前或未来的子元素附加一个或多个事件处理器
die()    移除所有通过 live() 函数添加的事件处理程序。
error()    触发、或将函数绑定到指定元素的 error 事件
event.isDefaultPrevented()    返回 event 对象上是否调用了 event.preventDefault()。
event.pageX    相对于文档左边缘的鼠标位置。
event.pageY    相对于文档上边缘的鼠标位置。
event.preventDefault()    阻止事件的默认动作。
event.result    包含由被指定事件触发的事件处理器返回的最后一个值。
event.target    触发该事件的 DOM 元素。
event.timeStamp    该属性返回从 197011 日到事件发生时的毫秒数。
event.type    描述事件的类型。
event.which    指示按了哪个键或按钮。
focus()    触发、或将函数绑定到指定元素的 focus 事件
keydown()    触发、或将函数绑定到指定元素的 key down 事件
keypress()    触发、或将函数绑定到指定元素的 key press 事件
keyup()    触发、或将函数绑定到指定元素的 key up 事件
live()    为当前或未来的匹配元素添加一个或多个事件处理器
load()    触发、或将函数绑定到指定元素的 load 事件
mousedown()    触发、或将函数绑定到指定元素的 mouse down 事件
mouseenter()    触发、或将函数绑定到指定元素的 mouse enter 事件
mouseleave()    触发、或将函数绑定到指定元素的 mouse leave 事件
mousemove()    触发、或将函数绑定到指定元素的 mouse move 事件
mouseout()    触发、或将函数绑定到指定元素的 mouse out 事件
mouseover()    触发、或将函数绑定到指定元素的 mouse over 事件
mouseup()    触发、或将函数绑定到指定元素的 mouse up 事件
one()    向匹配元素添加事件处理器。每个元素只能触发一次该处理器。
ready()    文档就绪事件(当 HTML 文档就绪可用时)
resize()    触发、或将函数绑定到指定元素的 resize 事件
scroll()    触发、或将函数绑定到指定元素的 scroll 事件
select()    触发、或将函数绑定到指定元素的 select 事件
submit()    触发、或将函数绑定到指定元素的 submit 事件
toggle()    绑定两个或多个事件处理器函数,当发生轮流的 click 事件时执行。
trigger()    所有匹配元素的指定事件
triggerHandler()    第一个被匹配元素的指定事件
unbind()    从匹配元素移除一个被添加的事件处理器
undelegate()    从匹配元素移除一个被添加的事件处理器,现在或将来
unload()    触发、或将函数绑定到指定元素的 unload 事件

 

 

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

     // $(document).ready(function () {
     //
     // });


     $(function () {

              $("#i1").css("color","red");
                // 双击事件
               $("#i1").dblclick(function () {
                    alert(123)
                });
                // 获取焦点,失去焦点事件
               $("#inp").focus(function () {
                   console.log("获取焦点")
               });
               $("#inp").blur(function () {
                   console.log("失去焦点");
               });
                // mouse事件
                $(".c1").mouseover(function () {
                    console.log("悬浮DIV")
                });

                $(".c1").mouseleave(function () {
                    console.log("离开DIV")
                });

                // select事件
                $("#inp").select(function () {
                    console.log("......")
                });

                // change事件

                 $("#pro").change(function () {

                });

                // submit事件:
                 $("#form").submit(function () {

                     //alert(123);
                     var val=$("[name='user']").val();
                     if (val.length<5){
                         // alert("长度不够!");
                         $("[name='user']").next().html("长度不够");

                         return false; // 终止后续事件
                     }

                 })

     })


        
    </script>
</head>
<body>


<div id="i1">DIV</div>
<input type="text" id="inp">

<div class="c1" style="width: 100px;height: 100px;background-color: gray"></div>
<hr>


<form action="" id="form">

    <p>用户名<input type="text" name="user"><span class="error"></span></p>
    <p>密码<input type="text" name="pwd"><span class="error"></span></p>
    <p><input type="submit" value="提交"></p>

</form>






</body>
</html>
演示案例

 

 

 

 

补充:

表格的增删改查代码参考

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
          *{
            margin: 0;
        }
        .shade{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: gray;
            opacity: 0.6;
        }

        .model{
            position: fixed;
            left:200px;
            top: 100px;
            width: 600px;
            height: 300px;
            background-color: white;
        }

        .hide{
            display: none;
        }
    </style>
</head>
<body>

<button class="addBtn">添加</button>
<table border="1">
     <thead>
           <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>班级</th>
        <th>操作</th>
    </tr>
     </thead>

    <tbody id="tbody">
         <tr>
        <td>张三</td>
        <td>23</td>
        <td>s19</td>
        <td>
            <button class="del">删除</button>
             <button class="del">编辑</button>
        </td>
    </tr>
         <tr>
            <td>李四</td>
            <td>23</td>
            <td class="active">s18</td>
            <td><button class="del">删除</button>
                <button class="del">编辑</button>
            </td>
         </tr>
         <tr>
            <td>王五</td>
            <td>28</td>
            <td>s19</td>
            <td>
                <button class="del">删除</button>
                <button class="del">编辑</button>
            </td>
         </tr>
    </tbody>

</table>

<div class="shade hide"></div>

<div class="model hide">
    <h3>添加学生信息:</h3>
    <form action="">
        <p>姓名 <input type="text" class="item"></p>
        <p>年龄 <input type="text" class="item"></p>
        <p>班级 <input type="text" class="item"></p>
        <input type="button" value="submit" id="subBtn">
    </form>
</div>



<script src="jquery-3.2.1.min.js"></script>
<script>

    // 删除事件
   $(".del").click(function () {
       console.log($(this));
       $(this).parent().parent().remove()
   });

    //  添加事件
    $(".addBtn").click(function () {
          $(".shade").show();
          $(".model").show()
    });

    //  $("#subBtn").click(function () {
    //      // 关闭对话框
    //      $(".shade").hide();
    //      $(".model").hide();
    //      // 获取用户输入值
    //      var arr=[];
    //      var $tr=$("<tr>");
    //      $(".item").each(function () {
    //          console.log($(this));
    //          arr.push($(this).val());
    //
    //          $td=$("<td>");  // <td></td>
    //          $td.html($(this).val());
    //          $tr.append($td)
    //      });
    //      $tr.append('<td><button class="del">删除</button></td>');
    //      console.log($tr[0]);
    //
    //      // 构建tr标签
    //
    //      $("#tbody").append($tr)
    //
    //
    //
    //
    //
    // })


     $("#subBtn").click(function () {
         // 关闭对话框
         $(".shade").hide();
         $(".model").hide();
         // 获取用户输入值
         var arr=[];

         $(".item").each(function () {
             console.log($(this));
             arr.push($(this).val());

         });
         console.log(arr);

         // 构建tr标签
         s='<tr><td>'+arr[0]+'</td><td>'+arr[1]+'</td><td>'+arr[2]+'</td><td><button class="del">删除</button></td></tr>'
         $("#tbody").append(s)





    })
</script>
</body>
</html>
表格的增删改查

 

 

模态对话框

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

    <style>
        .backend{
            width:100%;
            height: 2000px;
            background-color: lightblue;
        }
        *{
            margin: 0;
        }
        .shade{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: gray;
            opacity: 0.6;
        }

        .model{
            position: fixed;
            left:200px;
            top: 100px;
            width: 600px;
            height: 300px;
            background-color: white;
        }

        .hide{
            display: none;
        }
    </style>
</head>
<body>


<div class="backend">
 <button>注册</button>
</div>

<div class="shade hide"></div>

<div class="model hide">
    <h3>添加学生信息:</h3>
    <form action="">
        <p>姓名 <input type="text"></p>
        <p>年龄 <input type="text"></p>
        <p>班级 <input type="text"></p>
        <input type="button" value="submit" id="subBtn">
    </form>
</div>


<script src="jquery-3.2.1.min.js"></script>

<script>
    $("button").click(function () {
        $(".shade").show();
        $(".model").show()
    });

    $("#subBtn").click(function () {
         $(".shade").hide();
         $(".model").hide()
    })


</script>
</body>
</html>
模态对话框

 

 二级联动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select name="" id="pro">
    <option value="">请选择省份</option>
    <option value="hebei">河北省</option>
    <option value="henan">河南省</option>
    <option value="hunan">湖南省</option>
</select>
<select name="" id="city">
    <option value="">请选择城市</option>
</select>

<script src="jquery-3.2.1.min.js"></script>
<script>
    var data={"hebei":["石家庄","保定","廊坊"],"henan":["郑州","信阳","开封"],"hunan":["长沙","湘潭","张家界"]};

    $("#pro").change(function () {
        // console.log($(this).val());

        var citys=data[$(this).val()];
        //console.log(citys);

        // 清空操作
           console.log($("#city")[0].options.length);
           $("#city")[0].options.length=1;

        $.each(citys,function (i,j) {
            //console.log(i,j);
            var $option=$("<option>");
            $option.html(j);
            $("#city").append($option)
        })
    })
</script>
</body>
</html>
二级联动

 

posted @ 2017-12-19 22:27  小火星_Hirsi  阅读(341)  评论(0编辑  收藏  举报