JQuery

https://www.cnblogs.com/yuanchenqi/articles/6070667.html

<1>jQuery是由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。

<2>jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

<3>它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器

<4>jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。

<5>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 对象

$variable[0]:jquery对象转为dom对象      $("#msg").html(); $("#msg")[0].innerHTML
什么是jQuery 对象?

jquery的基础语法:$(selector).action() 

基本选择器      
$("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")
层级选择器      
$(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")
基本筛选器      
$("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")
属性选择器    
$('[id="div1"]')   $('["alex="sb"][id]')
表单选择器     
$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>hello</div>

<a href="">click</a>

<p id="p1" alex="sb">pppp</p>
<p id="p2" alex="sb">pppp</p>
<div class="outer">outer
    <div class="inner">
        inner
        <p>inner p</p>
    </div>
    <p>alex</p>
</div>
<div class="outer2">Yuan</div>
<p>xialv</p>

<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
    <li>4444</li>
    <li>4444</li>
    <li>4444</li>
</ul>

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

<script src="jquery-3.1.1.js"></script>  //引入jquery文件
<script>
    //基本选择器
    $("*").css("color","red")        通用选择器
    $("#p1").css("color","red")      id选择器
    $(".outer").css("color","red")   class选择器
    $("div").css("color","red")      标签选择器
    $(".inner,p,div").css("color","red")  多元素选择器

    //层级选择器
    $(".outer p").css("color","red")   //后代选择器:alex和inner p变红
    $(".outer>p").css("color","red")   //子代选择器:alex变红
    $(".outer+p").css("color","red")   //毗邻选择器(向下找且必须紧挨着):xialv变红
    $(".outer~p").css("color","red")   //兄弟选择器(向下找):xialv变红

    //基本筛选器
    $("li:first").css("color","red")    //第一个元素:1111变红
    $("li:eq(1)").css("color","red")    //指定哪个元素:2222变红
    $("li:gt(2)").css("color","red")    //大于几的位置:4444变红
    $("li:lt(2)").css("color","red")    //小于几的位置:1111 2222变红

    //属性选择器
    $("[alex='sb'][id='p1']").css("color","red")    //pppp变红

    //表单选择器
     //$("[type='text']").css("width","200px")
     $(":text").css("width","400px")   简写形式,注意只适用于input标签

</script>
</body>
</html>
选择器示例
查找筛选器:
$("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()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="">click</a>

<p id="p1" alex="sb">pppp</p>
<p id="p2" alex="sb">pppp</p>

<div class="outer">outer
    <div class="inner">
        inner
        <p>inner p</p>
    </div>
    <p>alex</p>
</div>
<div class="outer2">Yuan</div>
<p>xialv</p>

<ul>
    <li class="begin">1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
    <li>4444</li>
    <li id="end">4444</li>
    <li>4444</li>
</ul>

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

<script src="jquery-3.1.1.js"></script>
<script>
    //筛选器
    //$("li").eq(2).css("color","red");  //返回被选元素中带有指定索引号的元素
    //$("li").first().css("color","red");//返回被选元素的首个元素
    //$("li").last().css("color","red"); //返回被选元素的最后一个元素

    //查找筛选器

    //$(".outer").children("p").css("color","red");//返回被选元素的所有直接子元素:alex变红
    //$(".outer").find("p").css("color","red"); //返回被选元素的后代元素,一路向下直到最后一个后代:alex和inner p变红

    //$("li").eq(2).next().css("color","red");  //返回被选元素的下一个同胞元素:第一个‘4444’变红
    //$("li").eq(2).nextAll().css("color","red"); //返回被选元素的所有跟随的同胞元素:所有‘4444’变红
    //$("li").eq(2).nextUntil("#end").css("color","red");//返回介于两个给定参数之间的所有跟随的同胞元素:前两个‘4444’变红

    //$("li").eq(4).prev().css("color","red");  //指定位置的前一个:第一个‘4444’变红
    //$("li").eq(4).prevAll().css("color","red");//指定位置下面的全部:<li>中前四个变红
    //$("li").eq(4).prevUntil("li:eq(0)").css("color","red"); //指定开区间:2222,3333,4444变红

    //console.log($(".outer .inner p").parent().html()) //获得当前匹配元素集合中每个元素的父元素(找.outer .inner下的<P>的父代):inner <p>inner p</p>
   //$(".outer .inner p").parents().css("color","red"); //获得当前匹配元素集合中每个元素的祖先元素(元素是按照从最近的父元素向外的顺序被返回的):全变红
   //$(".outer .inner p").parentsUntil("body").css("color","red");//返回介于两个给定元素之间的所有祖先元素: outer~alex变红

    //$(".outer").siblings().css("color","red")//获得匹配集合中每个元素的同胞: 除了outer~alex都变红

</script>
</body>
</html>
查找筛选器示例 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .outer{
            height: 1000px;
            width: 100%;
        }
        .menu{
            float: left;
            background-color: beige;
            width: 30%;
            height: 500px;
        }
        .content{
            float: left;
            background-color: rebeccapurple;
            width: 70%;
            height: 500px;
        }
        .title{
            background-color: aquamarine;
            line-height: 40px;
        }
        .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>


<script src="jquery-3.1.1.js"></script>
<script>
    function show(self) {
        $(self).next().removeClass("hide");
        $(self).parent().siblings().children(".con").addClass("hide");
    }
</script>
</body>
</html>
实例之左侧菜单

 

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

    <script src="jquery-3.3.1.js"></script>
<script>
       function tab(self){
           var index=$(self).attr("xxx");
           $("#"+index).removeClass("hide").siblings().addClass("hide");
           $(self).addClass("current").siblings().removeClass("current");

       }
</script>
</body>
</html>
实例之tab切换

属性操作:

--------------------------属性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------CSS类
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------HTML代码/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("").css("color","red")
<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>
注意attr&prop
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="div1" con="c1"></div>
<input type="checkbox" checked="checked">是否可见            //默认勾选状态
<input type="checkbox">是否可见

<input type="text" value="123">
<div value="456"></div>

<div id="id1">
    uuuuu
    <p>ppppp</p>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
   console.log($("div").hasClass("div11"));  //检查被选元素是否包含指定的 class:  false

    console.log($("div").attr("con"))      //返回被选元素的属性值(检索HTML属性):c1
   console.log($("div").attr("con","c2")) //设置被选元素的属性值:c1变为c2
  <!--赋予属性用attr  , 固有属性用prop-->
    console.log($(":checkbox:first").attr("checked"))  // checked
    console.log($(":checkbox:last").attr("checked"))   //undefined
    console.log($(":checkbox:first").prop("checked"))  //设置或返回被选元素的属性和值(DOM属性):true
    console.log($(":checkbox:last").prop("checked"))   //false

    console.log($("div").prop("con"))  //找不到
    console.log($("div").prop("class")) //div1

    console.log($("#id1").html());  //设置或返回被选元素的内容(innerHTML):uuuuu  <p>ppppp</p>
    console.log($("#id1").text());  //设置或返回被选元素的文本内容:uuuuu  ppppp

    <!--有标签用html,纯文本用text-->
    console.log($("#id1").html("<h1>YUAN</h1>"))     //YUAN
    console.log($("#id1").text("<h1>YUAN</h1>"))       //<h1>YUAN</h1>

    <!--val()针对固有属性有value的-->
    console.log($(":text").val());  //返回或设置被选元素的值:123
    console.log($(":text").next().val())  //找不到“456”
    $(":text").val("789"); //更改值:原“123”变为“789”

    $("div").css({"color":"red","background-color":"green"}) //设置或返回被选元素的一个或多个样式属性


</script>
</body>
</html>
属性操作示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>1111</p>
<p>2222</p>
<p>3333</p>

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

<script>
    arr=[11,22,33];

<!--可以混用-->
    for (var i=0;i<arr.length;i++){
        $("p").eq(i).html(arr[i])     //11 22 33

    }

<!--each() 方法规定为每个匹配元素规定运行的函数。-->

//方式一 : $.each
    $.each(arr,function (x,y) {
        console.log(x);     //0 1 2
        console.log(y);     //11 22 33
    });
//方式二: $("E").each
    $("p").each(function () {
        console.log($(this));     //循环遍历<P>
        $(this).html("hello")     //更改<P>中内容为hello
    })

</script>


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


  <button onclick="selectall();">全选</button>
     <button onclick="cancel();">取消</button>
     <button onclick="reverse();">反选</button>
<hr>
     <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>

<script src="jquery-3.1.1.js"></script>
<script>
    function selectall() {
        $(":checkbox").each(function () {
            $(this).prop("checked",true)
        })
    }
    
    function cancel() {
         $(":checkbox").each(function () {
            $(this).prop("checked",false)
        })
    }

    function reverse() {
         $(":checkbox").each(function () {
            if($(this).prop("checked")){
                $(this).prop("checked",false)
            }

            else {
                $(this).prop("checked",true)
            }
        })
    }
</script>
</body>
</html>
实例之jquery实现正反选
<!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().addClass("hide");       写法一
        $(self).parent().prev().addClass("hide")

        //$(self).parent().parent().children(".models,.shade").addClass("hide")  写法二

        //$(self).parent().addClass("hide").prev().addClass("hide");           写法三

    }
</script>
</body>
</html>
实例之jquery实现模态对话框

文档处理:

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


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

</div>

<button>add</button>
<script src="jquery-3.1.1.js"></script>
<script>
        $("button").click(function () {           //绑定click事件
          // $(".c1").append("<h1>HELLO YUAN</h1>")    //添加h1标签:点击按钮add页面就会在PPP后面添加HELLO YUAN

           var $ele=$("<h1></h1>");    //创建h1标签(可以只写<h1>):点击按钮add页面就会在PPP后面添加红色的HELLO WORLD!
           $ele.html("HELLO WORLD!");
           $ele.css("color","red");
           $(".c1").append($ele);

  //      })

//内部插入:
<!--append() 方法在被选元素的结尾(仍然在内部)插入指定内容。append() 和 appendTo() 方法执行的任务相同。不同之处在于:内容和选择器的位置,以及 append() 能够使用函数来附加内容。-->
<!--prepend() 方法在被选元素的开头(仍位于内部)插入指定内容。prepend() 和 prependTo() 方法作用相同。差异在于语法:内容和选择器的位置,以及 prependTo() 无法使用函数来插入内容。-->
            $(".c1").append($ele);
            $ele.appendTo(".c1")
            $(".c1").prepend($ele);    //点击按钮add页面就会在PPP前面添加红色的HELLO WORLD!
            $ele.prependTo(".c1")

//外部插入 (显示不变,插入标签位置变化):
<!--after() 方法在被选元素后插入指定的内容。insertAfter() 方法在被选元素之后插入 HTML 标记或已有的元素。-->
<!--before() 方法在被选元素之前插入内容。insertBefore() 方法在被选元素之前插入 HTML 标记或已有的元素-->
            $(".c1").after($ele)
            $ele.insertAfter(".c1")
            $(".c1").before($ele)
            $ele.insertBefore(".c1")
//替换:
<!--replaceWith() 方法用指定的 HTML 内容或元素替换被选元素-->
            $("p").replaceWith($ele)   //"PPP"替换为红色的HELLO WORLD!

//删除与清空:
<!--empty() 方法从被选元素移除所有内容,包括所有文本和子节点。-->
<!--remove() 方法移除被选元素,包括所有文本和子节点。-->
            $(".c1").empty()   //清空 <p>PPP</p>
            $(".c1").remove()   //清空整个<div>: <div class="c1">  <p>PPP</p>

//clone:
             var $ele2= $(".c1").clone();  //克隆PPP并放到它的下面,但是会出现一个问题:克隆出来的还是c1多点击几次add会克隆出很多
             $(".c1").after($ele2)
       })
</script>
</body>
</html>
文档处理示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div class="outer">
    <div class="item">
        <button onclick="add(this)">+</button>
        <input type="text">
    </div>

</div>


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

    function add(self) {

        var $clone_obj=$(self).parent().clone();  //克隆button的父类-整个<item>
        $clone_obj.children("button").html("-").attr("onclick","remove_obj(this)"); //把克隆的内容按钮+改成—并重新设置属性
        $(".outer").append($clone_obj)   //把克隆内容添加到outer下面
    }

    function remove_obj(self) {
        $(self).parent().remove()   //移除button的父类-整个<item>
    }
</script>
</body>
</html>
实例之复制样式条

 css操作:

CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])  返回或设置匹配元素相对于文档的偏移(位置)
        $("").position()             返回匹配元素相对于父元素的位置(偏移)
        $("").scrollTop([val])       设置或返回被选元素的垂直滚动条位置
        $("").scrollLeft([val])      设置或返回匹配元素的滚动条的水平位置
    尺寸
        $("").height([val|fn])  设置或返回元素的高度
        $("").width([val|fn])   设置或返回元素的宽度
        $("").innerHeight()     返回元素的高度(包含 padding)
        $("").innerWidth()      返回元素的宽度(包含 padding)
        $("").outerHeight([soptions]) 返回元素的高度(包含 padding 和 border)
        $("").outerWidth([options])  返回元素的宽度(包含 padding 和 border)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div1,.div2{
            width: 200px;
            height: 100px;
        }
        .div1{
            border: 5px solid rebeccapurple;
            padding: 20px;
            margin: 2px;
            background-color: antiquewhite;
        }
        .div2{
            background-color: rebeccapurple;
        }

        .outer{
            position: relative;
        }
    </style>
</head>
<body>

<div class="div1"></div>

<div class="outer">
<div class="div2"></div>
</div>


<script src="jquery-3.1.1.js"></script>
<script>
// offset() 
     console.log($(".div1").offset().top);  //2
     console.log($(".div1").offset().left); //2

     console.log($(".div2").offset().top);  //154
     console.log($(".div2").offset().left); //0

//position() 
     console.log($(".div1").position().top);  //0
     console.log($(".div1").position().left); //0

     console.log($(".div2").position().top);  //154
     console.log($(".div2").position().left); //0


     console.log($(".div1").height());  //:100
     console.log($(".div1").innerHeight());  //:140
     console.log($(".div1").outerHeight()); // 150
     console.log($(".div1").outerHeight(true));// 154




</script>
</body>
</html>
css操作示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div2{
            width: 100%;
            height: 800px;
        }
        .div1{
            width: 40%;
            height: 150px;
            background-color: antiquewhite;
            overflow: auto;
        }
        .div2{
            background-color: rebeccapurple;
        }

         .returnTop{
             position: fixed;        //定位类型:绝对定位
             right: 20px;
             bottom: 20px;
             width: 90px;
             height: 50px;
             background-color: gray;
             color: white;
             text-align: center;    //元素文本的水平对齐方式:居中
             line-height: 50px;
         }

         .hide{
             display: none;
         }

    </style>
</head>
<body>


<div class="div1">
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
</div>

<div class="div2">
    <button onclick="returnTop()">return</button>
</div>

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

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


    window.onscroll=function () {           //onscroll 事件在元素滚动条在滚动时触发。


        console.log($(window).scrollTop());

        if($(window).scrollTop()>300){
            $(".returnTop").removeClass("hide")
        }else {
            $(".returnTop").addClass("hide")
        }


    };

    function returnTop() {
        $(window).scrollTop(0)

    }

    $(".div2 button").click(function () {
         $(".div1").scrollTop(0)
    })



</script>
</body>
</html>
实例之返回顶部

 事件绑定与委托:

页面载入
    ready(fn)  //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
    $(document).ready(function(){}) -----------> $(function(){})

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

    //  .on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如:
    //  $('ul').on('click', 'li', function(){console.log('click');})就是筛选出ul下的li给其绑定
    //  click事件;

    [selector]参数的好处:
        好处在于.on方法为动态添加的元素也能绑上指定事件;如:

        //$('ul li').on('click', function(){console.log('click');})的绑定方式和
        //$('ul li').bind('click', function(){console.log('click');})一样;我通过js给ul添加了一个
        //li:$('ul').append('<li>js new li<li>');这个新加的li是不会被绑上click事件的

        //但是用$('ul').on('click', 'li', function(){console.log('click');}方式绑定,然后动态添加
        //li:$('ul').append('<li>js new li<li>');这个新生成的li被绑上了click事件
    
    [data]参数的调用:
             function myHandler(event) {
                alert(event.data.foo);
                }
             $("li").on("click", {foo: "bar"}, myHandler)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>


</head>
<body>

<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
</ul>

<button>add</button>
<script src="jquery-3.1.1.js"></script>
<script>
// 事件准备加载方式一:
    $(document).ready(function () {
         $("ul li").html(5);             //li中文本均改成5
    });
// 事件准备加载方式二:
     $(function () {
        $("ul li").html(5);
     });

//事件绑定的三种简单形式及解除:
    var eles=document.getElementsByTagName("li")
    eles.onclick=function () {
        alert(123)
    }

    $("ul li").click(function () {
        alert(6666)
    });

    $("ul li").bind("click",function () {
        alert(777)
    });

    // $("ul li").unbind("click")   //解除绑定

//事件委托:
    $('ul').on("click","li",function () {
       alert(999);
    });


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

            var $ele=$("<li>");
            var len=$("ul li").length;
            $ele.html((len+1)*1111);
            $("ul").append($ele)
    });

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

 动画效果:

 //hide() 和 show() 方法用来隐藏和显示 HTML 元素
toggle() 方法来切换 hide() 和 show() 方法。显示被隐藏的元素,并隐藏已显示的元素
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.1.1.js"></script>
    <title>Title</title>
</head>
<body>
<div>hello</div>

<button onclick="f1()">显示</button>
<button onclick="f2()">隐藏</button>
<button onclick="f3()">切换</button>
<script>

    function f1() {
      $("div").show(1000,function () {         //1000指显示速度ms
        //  alert("show")
      })
    }

  function f2() {
      $("div").hide(1000,function () {
         // alert(1243)
      })
    }

     function f3() {
      $("div").toggle(1000)
    }
</script>

</body>
</html>
显示隐藏切换
//slideUp() 方法用于向上滑动元素,slideDown() 方法用于向下滑动元素
slideToggle() 方法可以在 slideDown() 与 slideUp() 方法之间进行切换:
如果元素向下滑动,则 slideToggle() 可向上滑动它们。如果元素向上滑动,则 slideToggle() 可向下滑动它们。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.1.1.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">hello world</div>

</body>
</html>
滑动
//fadeIn() 用于淡入已隐藏的元素;fadeOut() 方法用于淡出可见元素;fadeTo() 方法允许渐变为给定的不透明度(值介于 0 与 1 之间)。
fadeToggle() 方法可以在 fadeIn() 与 fadeOut() 方法之间进行切换:
如果元素已淡出,则 fadeToggle() 会向元素添加淡入效果。如果元素已淡入,则 fadeToggle() 会向元素添加淡出效果。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.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 lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.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>
回调函数示例

 扩展方法(插件机制):

<script>
    
$.extend(object)      //为JQuery 添加一个静态方法。
$.fn.extend(object)   //为JQuery实例添加一个方法。


    jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
        });
    console.log($.min(3,4));

//-----------------------------------------------------------------------
$.fn.extend({
    "print":function(){
        for (var i=0;i<this.length;i++){
            console.log($(this)[i].innerHTML)
        }

    }
});

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

<p>111</p>
<p>222</p>
<p>333</p>

<script>



//方法一:
    $.extend({
        Myprint:function () {
            console.log("hello")
        }
    });

    $.Myprint();     //hello

//方法二:
   $.fn.extend({
      GetText:function () {
            for(var i=0;i<this.length;i++){
                console.log(this[i].innerHTML)
            }

            $.each($(this),function (x,y) {

                //console.log(y.innerHTML)
                //console.log($(y).html())
            })

        }
    });

   $("p").GetText()   //111 222 333

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

           *{
               margin: 0;
               padding: 0;
           }
        .box{
            width: 500px;
            height: 200px;
            position: absolute;
        }

        .title{
            background-color: black;
            height: 50px;
            width: 500px;
            line-height: 50px;
            text-align: center;
            color: white;
        }
        .content{
            width: 500px;
            height: 150px;
            background-color: antiquewhite;
        }
    </style>


    <script>
        $(function () {

          $(".title").mouseover(function () {                //当鼠标指针位于元素上方时,会发生 mouseover 事件
              $(this).css("cursor","pointer");
        }).mousedown(function (e) {                          //当鼠标指针移动到元素上方,并按下鼠标按键时,会发生 mousedown 事件。

                  var eve = e || window.event;
                // 原始鼠标横纵坐标位置

                  var old_m_x=eve.clientX;
                  var old_m_y=eve.clientY;
//                  console.log(old_x);
//                  console.log(old_y);

                 var old_box_y=$(this).parent().offset().top ;
                 var old_box_x=$(this).parent().offset().left ;

                  $(this).bind("mousemove",function (eve) {
                      var new_m_x=eve.clientX;
                      var new_m_y=eve.clientY;

                      var m_x=new_m_x-old_m_x;
                      var m_y=new_m_y-old_m_y;



                  //$(".box").css({"top":old_box_y+m_y+"px","left":old_box_x+m_x+"px"})

                var x = old_box_x + m_x;
                var y = old_box_y + m_y;

                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');
                  })
              })
          }).mouseout(function(){
            $(this).unbind('mousemove');
        })

    </script>
</head>
<body>


<div class="box">
    <div class="title">标题</div>
    <div class="content">内容</div>
</div>

</body>
</html>
跟随鼠标移动面板实例 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.1.1.js"></script>
    <title>Title</title>


    <style>
            .outer{                           /*最外框跟图片大小一致,居中*/
                width: 790px;
                height: 340px;
                margin: 80px auto;
                position: relative;
            }

            .img li{
                 position: absolute;
                 list-style: none;
                 top: 0;
                 left: 0;
            }

           .num{
               position: absolute;
               bottom: 18px;
               left: 270px;
               list-style: none;        /*去掉列表的原点样式*/


           }

           .num li{
               display: inline-block;
               width: 18px;
               height: 18px;
               background-color: white;
               border-radius: 50%;
               text-align: center;
               line-height: 18px;
               margin-left: 4px;
           }

           .btn{
               position: absolute;
               top:50%;
               width: 30px;
               height: 60px;
               background-color: lightgrey;
               color: white;

               text-align: center;
               line-height: 60px;
               font-size: 30px;
               opacity: 0.7;     /* opacity 属性设置元素的不透明级别,从 0.0 (完全透明)到 1.0(完全不透明)*/
               margin-top: -30px;

               display: none;

           }

           .left{
               left: 0;
           }

           .right{
               right: 0;
           }

         .outer:hover .btn{             /* //:hover 选择器用于选择鼠标指针浮动在上面的元素*/
              display: block;
          }

        .num .active{
            background-color: red;
        }
    </style>

</head>
<body>


      <div class="outer">
          <ul class="img">
              <li><a href=""><img src="img/1.jpg" alt=""></a></li>
              <li><a href=""><img src="img/2.jpg" alt=""></a></li>
              <li><a href=""><img src="img/3.jpg" alt=""></a></li>
              <li><a href=""><img src="img/4.jpg" alt=""></a></li>
              <li><a href=""><img src="img/5.jpg" alt=""></a></li>
              <li><a href=""><img src="img/6.jpg" alt=""></a></li>
          </ul>

          <ul class="num">
              <!--<li class="active"></li>-->
              <!--<li></li>-->
              <!--<li></li>-->
              <!--<li></li>-->
              <!--<li></li>-->
              <!--<li></li>-->
          </ul>

          <div class="left  btn"> < </div>
          <div class="right btn"> > </div>

      </div>

<script>
    var i=0;
//  通过jquery自动创建按钮标签

    var img_num=$(".img li").length;

    for(var j=0;j<img_num;j++){
        $(".num").append("<li></li>")
    }

    $(".num li").eq(0).addClass("active");


// 手动轮播
    $(".num li").mouseover(function () {
        i=$(this).index();
        $(this).addClass("active").siblings().removeClass("active");
        $(".img li").eq(i).stop().fadeIn(200).siblings().stop().fadeOut(200)

    });


// 自动轮播
    var c=setInterval(GO_R,1500);


    function GO_R() {

        if(i==img_num-1){
            i=-1
        }
         i++;
         $(".num li").eq(i).addClass("active").siblings().removeClass("active");
         $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000)

    }


    function GO_L() {
        if(i==0){
            i=img_num
        }
         i--;
         $(".num li").eq(i).addClass("active").siblings().removeClass("active");
         $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000)


    }
    $(".outer").hover(function () {
        clearInterval(c)
    },function () {
        c=setInterval(GO_R,1500)
    });
    
// button 加定播 
    $(".right").click(GO_R);
    $(".left").click(GO_L)


</script>
</body>
</html>
京东轮播图实例

 

posted @ 2018-10-17 16:39  一只小妖  阅读(74)  评论(0)    收藏  举报