3.11版jquery

一 jquery是什么?


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


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


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


        (IE 6.0+,FF 1.5+,Safari 2.0+,Opera 9.0+)。


    <4>jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documents、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的基础语法:$(selector).action()


三 寻找元素(选择器和筛选器) 


3.1   选择器




3.1.1 基本选择器 


选择器 实例 选取

* $("*") 所有元素

#id $("#lastname") id="lastname" 的元素

.class $(".intro") 所有 的元素

element $("p") 所有 <p> 元素

.class.class $(".intro.demo") 所有 且 的元素

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <div id="div">hello div</div>

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

    <a id="p1">pppp</a>

    <div>

         outer

        <div>

             inner

            <p>inner p</p>

        </div>

    </div>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

 $("*").css("font-size",'20px');

 $("a").css("color","red");

 $("#p1").css("color","yellow");

 $(".outer").css("color","blue");

 $(".inner .p").css("color","green")

</script>

</html>

3.1.2 层级选择器  


$(".outer div")             向下所有div标签


$(".outer>div")           


$(".outer+div")          下面


$(".outer~div")          向下所有div标签(包括外层)


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <p>out p</p>

    <div>outer 0 div</div>

    <div>outer 1 div

        <div>

 inner div

            <p>inner p</p>

        </div>

        <div>

 inner 2 div

        </div>

        <p>outer p</p>

    </div>

    <div>outer2 div</div>

    <p>xiao lv</p>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

 $(".outer p").css("color","red");

 $(".outer>div").css("color","yellow");

 $(".outer+div").css("color","blue");

 $(".outer~p").css("color","green");

</script>

</html>

3.1.3 基本筛选器(少用)     


$("li:first")                  找到第一个li标签


$("li:last")                  找到最后一个li标签


$("li:eq(2)")               找到第三个li标签


$("li:even")                所有偶数标签


$("li:odd")                 所有基数标签


$("li:gt(1)")                从第二个li标签之后


$("li:lt(3)")                从第四个li标签之前


3.1.4 属性选择器    


$("[id='div1']")               找到指定id标签


$("['lily'='nb'][id]")         找到所有指定标签,然后根据id筛选指定标签


$("[ssid ='"+sid+"']")     带变量属性筛选器,sid一个变量,ssid标签名


3.1.5 表单选择器    


$("[type='text']")----->$(":text") 


$("input:checked")            注意只适用于input标签  


3.2 筛选器


3.2.1  过滤筛选器(推荐使用)     


$("li").eq(2)                      找到第三个li标签


$("li").first()                      找到第一个li标签


$("li").last()                       找到最后一个li标签


$("ul li").hasclass("test")        判断标签是否存在(结果是true or false)


.hasclass()示例:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <div>hello div1</div>

</body>

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

<script>

 document.write($("div").hasClass("div1"))

</script>

</html>

 3.2.2  查找筛选器


$("div").children(".test")         查找div标签的儿子class=test的标签


$("div").find(".test")                查找div标签下属所有class=test的标签


$(".test").next()                       查找class=test标签的下一个标签


$(".test").nextAll()                   查找class=test标签的下面所有标签


$(".test").nextUntil(".end")               查找class=test标签下面所有标签直到找到class=end标签停止


$("div").prev()                          查找class=test标签的上一个标签


$("div").prevAll()                      查找class=test标签的上面所有标签


$("div").prevUntil()                   和$(".test").nextUntil(".end")  相反


$(".test").parent()                    查找class=test标签的父亲标签


$(".test").parents()                   查找class=test标签的所有父亲标签


$(".test").parentUntil() 


$("div").siblings()                    查找div标签的所有兄弟标签




左侧菜单联动


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <style>

 .outer{

            height: 1000px;

 width: 100%;

 }

        .menu{

            float: left;

 background-color: #8ca1c1;

 width: 30%;

 height: 100%;

 }

        .content{

            float: right;

 background-color: #d47f39;

 width: 70%;

 height: 100%;

 }

        .hide{

            display: none;

 }

        .title{

            background-color: antiquewhite;

 line-height: 50px;

 color: #2459a2;

 }

    </style>

</head>

<body>

    <div>

        <div>

            <div>

                <div onclick="show(this);">菜单一</div>

                <div>

                    <div>子菜单一</div>

                    <div>子菜单一</div>

                    <div>子菜单一</div>

                </div>

            </div>

            <div>

                <div onclick="show(this);">菜单二</div>

                <div class="con hide">

                    <div>子菜单二</div>

                    <div>子菜单二</div>

                    <div>子菜单二</div>

                </div>

            </div>

            <div>

                <div onclick="show(this);">菜单三</div>

                <div class="con hide">

                    <div>子菜单三</div>

                    <div>子菜单三</div>

                    <div>子菜单三</div>

                </div>

            </div>

        </div>

        <div></div>

    </div>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

 function  show(self){

        $(self).next().removeClass('hide');

 $(self).parent().siblings().children(".con").addClass("hide");

 }

</script>

</html>

四 操作元素(属性,css,文档处理)


4.1 属性操作


--------------------------属性


$("").attr();                     增加/修改属性  对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。


$("").removeAttr();


$("").prop();                    对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。


$("").removeProp();


--------------------------CSS类


$("").addClass(class|fn)                增加class属性


$("").removeClass([class|fn])        移除class


--------------------------HTML代码/文本/值


$("").html([val|fn])                        相当于js innerHTML


$("").text([val|fn])                         相当于js innerText


$("").val([val|fn|arr])                     相当于js value(只能取到标签的固有值value),主要用于input select option


---------------------------


$("").css("color","red")                修改标签的样式


attr()  prop()区别


<input id="chk1" type="checkbox" />是否可见

<input id="chk2" type="checkbox" checked="checked" />是否可见

<script>

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



javsscript和jquery相同功能的方法的名字(左js,右jquery)


.innerHTML        .html()


jquery循环遍历两种方式:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<p>11111</p>

<p>11111</p>

<p>11111</p>

<p>11111</p>

<div>22222</div>

<div>22222</div>

<div>22222</div>

<div>22222</div>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

//     js和jquery可以混用

 arr = [11,22,33,44];

 for (var i=0;i<arr.length;i++){

        $('p').eq(i).html(arr[i])

    }

//  第一种循环遍历方式

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

        document.write(x,' ');

 document.write(y,"<br>");

 });

//    第二种循环遍历方式

 $("div").each(function(){

        document.write($(this),"<br>");

 $(this).html('hello 第二种循环遍历方式')

    })

</script>

</html>

jquery正反选示例:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<button onclick="selectall();">全选</button>

     <button onclick="cancel();">取消</button>

     <button onclick="reverse();">反选</button>

     <table border="1">

         <tr>

             <td><input type="checkbox"></td>

             <td>111</td>

         </tr>

         <tr>

             <td><input type="checkbox"></td>

             <td>222</td>

         </tr>

         <tr>

             <td><input type="checkbox"></td>

             <td>333</td>

         </tr>

         <tr>

             <td><input type="checkbox"></td>

             <td>444</td>

         </tr>

     </table>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.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(){

            $(this).prop("checked",!$(this).prop("checked"))

        })

    }

</script>

</html>

实例之模态对话框


<!DOCTYPE html>

<html>

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

    <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 typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

    function action1(self){

        $(self).parent().siblings().removeClass("hide");

    }

    function action2(self){

        $(self).parent().parent().children(".models,.shade").addClass("hide")

    }

</script>

</body>

</html>

4.2 文档处理


内部插入(父亲插入标签到儿子)


    $("").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>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<div>

    <p>PPP</p>

</div>

<button>add</button>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

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

        $('.c1').append("<h1>append hello world</h1>");

 var $ele=$("<h1></h1>");      //创建标签

 $ele.html("append Hello word 方法2");

 $ele.css("color",'red');

 $('.c1').append($ele);

 var $ele1=$("<h1></h1>");

 $ele1.html("appendto Hello word 方法3");

 $ele1.css("color",'red');

 $ele1.appendTo('.c1');

 var $ele2=$("<h1></h1>");

 $ele2.html("prepend Hello word 方法4");

 $ele2.css("color",'red');

 $(".c1").prepend($ele2);

 var $ele3=$("<h1></h1>");

 $ele3.html("prependto Hello word 方法5");

 $ele3.css("color",'red');

 $ele3.prependTo('.c1');

 })

</script>

</html>

外部插入代码示例:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<div>

    <p>PPP</p>

</div>

<button>add</button>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

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

        var $ele=$("<h1></h1>");      //创建标签

 $ele.html("after Hello word");

 $ele.css("color",'red');

 $('.c1').after($ele);

 var $ele1=$("<h1></h1>");

 $ele1.html("before Hello word");

 $ele1.css("color",'red');

 $('.c1').before($ele1);

 });

 var $ele2=$("<h1></h1>");

 $ele2.html("insertAfter Hello word");

 $ele2.css("color",'red');

 $ele2.insertAfter(".c1");

</script>

</html>

替换代码示例:




删除代码示例:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<div>

    <p>PPP</p>

</div>

<div>

    <p>PPP</p>

</div>

<button>add</button>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

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

        $('.c1').empty();

 $(".c2").remove();

 })

</script>

</html>

复制(复制样式条)代码示例:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<div>

    <div>

        <button onclick="add(this)">+</button>

        <input type="text">

    </div>

</div>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

 function add(self){

        var $clone_obj=$(self).parent().clone();

        //  把value值清空

        $clone_obj.children(':text').prop("value","");

        $clone_obj.children("button").html('-').attr("onclick","remove_obj(this)");

        $(".outer").append($clone_obj);

 }

    function remove_obj(self){

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

    }

</script>

</html>

4.3 css操作


CSS样式


        $("").css(name|pro|[,val|fn])        样式修改


位置方法


        $("").offset([coordinates])            获取对象    获取对象具体信息方法:.offset().top   .offset().left


                                                             相对于视口的偏移量


        $("").position()                             相对于已定位的父标签的偏移量


        $("").scrollTop([val])                     必须要有监听事件


        $("").scrollLeft([val])                     必须要有监听事件


尺寸方法


        $("").height([val|fn])                     标签高度


        $("").width([val|fn])                      标签长度


        $("").innerHeight()                       标签内部高度(包括padding)


        $("").innerWidth()                        标签内部宽度


        $("").outerHeight([soptions])       标签外部高度(包括边框,margin)


        $("").outerWidth([options])          标签外部宽度


jquery 返回顶部代码示例:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

<style>

 *{

   margin: 0;

   padding:0;

 }

 .div1,.div2{

   width: auto;

     height: 800px;

 }

        .div1{

            background-color: green;

 }

        .div2{

            background-color: #e59373;

 }

        .returnTop{

            position: fixed;

 right: 20px;

 bottom: 20px;

 width: 80px;

 height: 50px;

 background-color: #99aecb;

 line-height: 50px;

 font-size: 14px;

 text-align: center;

 }

        .hide{

            display: none;

 }

    </style>

</head>

<body>

    <div></div>

    <div></div>

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

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

 window.onscroll=function(){

        var current=$(window).scrollTop();

 console.log(current);

 if(current>100){

            $(".returnTop").removeClass("hide")

        }

        else {

            $(".returnTop").addClass("hide")

        }

    };

 function returnTop(){

        $(window).scrollTop(0);

 }

</script>

</html>

五 事件


5.1 页面载入


        ready(fn)  //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。


        $(document).ready(function(){})   -----简写------> $(function(){})


代码示例:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <ul>

        <li>1111</li>

        <li>2222</li>

        <li>3333</li>

        <li>4444</li>

        <li>5555</li>

    </ul>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

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

//        $("ul li").html(5555);

//    });

//    简写

 $(function(){

        $("ul li").html(5555);

 })

</script>

</html>

事件绑定代码示例


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <ul>

        <li>1111</li>

        <li>2222</li>

        <li>3333</li>

        <li>4444</li>

        <li>5555</li>

    </ul>

    <button>add</button>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

    //    简写

    //    $("ul li").click(function(){

    //        alert('11111111111');

    //    });

    //    绑定事件全写

    $("ul li").bind("click",function () {

        alert('2222222222');

    });

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

        var $ele = $('<li></li>');

        var len = $("ul li").length;

        $ele.html((len + 1) * 1111);

        $('ul').append($ele)

    });

    //    解除绑定

    //    $("ul  li").unbind("click")

</script>

</html>

事件代码坑注意事项:


        1、绑定时间不能使用索引取值,只能使用seq如下面写法是错误:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <ul>

        <li>1111</li>

        <li>2222</li>

        <li>3333</li>

        <li>4444</li>

        <li>5555</li>

    </ul>

    <button>add</button>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

btns =$('.li')

console.log(btns)

for (i=0;i<btns.length;i++){

    console.log(btns[i])

    console.log('使用索引绑定时间')  

    btns[i].click(function (){

        alert('11111111')

    })

  console.log('事件结束')

}

</script>

5.2 事件委托


        $("").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',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>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <ul>

        <li>1111</li>

        <li>2222</li>

        <li>3333</li>

        <li>4444</li>

        <li>5555</li>

    </ul>

    <button>add</button>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

//    事件委托简写

//    $("ul").on("click","li",function(){

//        alert('11111111111');

//    });

//    事件委托全写

 $("ul").on("li").bind("click",function(){

        alert('2222222222');

 });

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

        var $ele=$('<li></li>');

 var len=$("ul li").length;

 $ele.html((len+1)*1111);

 $('ul').append($ele)

    });

//    解除绑定

//    $("ul  li").unbind("click")

</script>

</html>

面板拖动代码示例


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title></title>

</head>

<body>

<div style="border: 1px solid #ddd;width: 600px;position: absolute;">

    <div id="title" style="background-color: black;height: 40px;color: white;">

 标题

    </div>

    <div style="height: 300px;">

 内容

    </div>

</div>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

 $(function () {

        // 页面加载完成之后自动执行

 $('#title').mouseover(function () {

            $(this).css('cursor','move');

 }).mousedown(function (e) {

            //console.log($(this).offset());

 var _event = e || window.event;

 // 原始鼠标横纵坐标位置

 var ord_x = _event.clientX;

 var ord_y = _event.clientY;

 var parent_left = $(this).parent().offset().left;

 var parent_top = $(this).parent().offset().top;

 $(this).bind('mousemove',function (e) {

                var _new_event = e || window.event;

 var new_x = _new_event.clientX;

 var new_y = _new_event.clientY;

 var x = parent_left + (new_x - ord_x);

 var y = parent_top + (new_y - ord_y);

 $(this).parent().css('left',x + 'px');

 $(this).parent().css('top',y + 'px');

 })

        }).mouseup(function () {

            $(this).unbind('mousemove');

 });

 })

</script>

</body>

</html>

六 动画效果


6.1 显示、隐藏、切换方法:


.show()        显示            .show(1000)        表示花费1秒钟时间完全显示


.hide()          隐藏


.toggle()      切换(显示和隐藏相互切换)


显示隐藏代码示例


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<div>hello</div>

<button onclick="f1()">显示</button>

<button onclick="f2()">隐藏</button>

<button onclick="f3()">切换</button>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script>

 function f1(){

        $('div').show(1000)

    }

    function f2(){

        $("div").hide(1000)

    }

    function f3(){

        $("div").toggle(1000)

    }

</script>

</html>

 6.2 向下滑动显示、隐藏、切换方法:


slideDown()        向下显示


slideUp()             向上隐藏


slideToggle()       显示/隐藏切换


向下滑动显示、隐藏、切换代码示例


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<style>

        #content{

            text-align: center;

 background-color: lightblue;

 border:solid 1px red;

 display: none;

 padding: 50px;

 }

    </style>

<body>

    <div id="slideDown">出现</div>

    <div id="slideUp">隐藏</div>

    <div id="slideToggle">toggle</div>

    <div id="content">hello world</div>

</body>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.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>

</html>

6.3 淡入淡出


fadeIn()               淡入已隐藏的元素


fadeOut()            淡出可见元素


fadeToggle()        在 fadeIn() 与 fadeOut() 方法之间进行切换


fadeTo()               允许渐变为给定的不透明度(值介于 0 与 1 之间)


代码示例


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<style>

        #content{

            text-align: center;

 background-color: lightblue;

 border:solid 1px red;

 display: none;

 padding: 50px;

 }

    </style>

<body>

      <button id="in">淡入</button>

      <button id="out">淡出</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>

<script typet="text/javascript" src="http://code.jquery.com/jquery-latest.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>

</html>

6.4 回调函数


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.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>

七 扩展方法 (插件机制)


7.1 用JQuery写插件时,最核心的方两个方法


<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(){

            console.log($(this).html())

        }

    });

    $("p").print();

    

</script>

7.2 定义作用域


定义一个JQuery插件,首先要把这个插件的代码放在一个不受外界干扰的地方。如果用专业些的话来说就是要为这个插件定义私有作用域。外部的代码不能直接访问插件内部的代码。插件内部的代码不污染全局变量。在一定的作用上解耦了插件与运行环境的依赖。


(function(a,b){return a+b})(3,5)

       (function ($) { })(jQuery);

//相当于

        var fn = function ($) { };

        fn(jQuery);

7.3  默认参数


定义了jQuery插件之后,如果希望某些参数具有默认值,那么可以以这种方式来指定。


/step01 定义JQuery的作用域

(function ($) {

    //step03-a 插件的默认值属性

    var defaults = {

        prevId: 'prevBtn',

        prevText: 'Previous',

        nextId: 'nextBtn',

        nextText: 'Next'

        //……

    };

    //step06-a 在插件里定义方法

    var showLink = function (obj) {

        $(obj).append(function () { return "(" + $(obj).attr("href") + ")" });

    }

    //step02 插件的扩展方法名称

    $.fn.easySlider = function (options) {

        //step03-b 合并用户自定义属性,默认属性

        var options = $.extend(defaults,options);

        //step4 支持JQuery选择器

        //step5 支持链式调用

        return this.each(function () {

            //step06-b 在插件里定义方法

            showLink(this);

        });

    }

})(jQuery);

8.新建标签


<script>

var link  = $("<a/>")  

</script>


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1.第一步 设置响应头 header(&#39;Access-Control-Allow-Origin:*&#39;); //支持全域名访问,不安全,部署后需要固定限制为客户端网址 header(&#39;Access-Control-Allow-Methods:POST,GET,OPTIONS,D
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的值,并返回其索引值。如果数组中不存在该值,则返回-1; $.inArray(value,array) --value是要查找的值,array是被查找的数组。 有如下实例: &lt;!DOCTYPE html&gt; &l
jquery.serializejson.min.js的妙用 关于这个jquery.serializejson.min.js插件来看,他是转json的一个非常简单好用的插件。 前端在处理含有大量数据提交的表单时,除了使用Form直接提交刷新页面之外,经常碰到的需求是收集表单信息成数据对象,Ajax提
JS 将form表单数据快速转化为object对象(json对象) jaymou 于 2020-03-03 11:11:05 发布 3534 收藏 3 分类专栏: 前端 文章标签: javascript jquery 版权 前端 专栏收录该内容 5 篇文章0 订阅 订阅专栏 直接上代码 /** *
jQuery的区别:$().click()和$(document).on(&#39;click&#39;,&#39;要选择的元素&#39;,function(){})的不同 文章地址:https://www.cnblogs.com/sqh17/p/7746418.html 解决:动态创建的元素的事件
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http://www.helloweba.com/view-blog-282.html 左右加减数字 像京东提交订单时目前使用的是左右加减数字的效果,这个效果直接明了,操作简单。我们使用jquery.spinner.js插件实
layui标签或一般标签均可&lt;div class=&quot;layui-form-item&quot;&gt; &lt;label class=&quot;layui-form-label&quot;&gt;异地仓名称&lt;/label&gt; &lt;div class=&quot;la
网上对于select option 动态添加修改如下, $(&quot;#selectId&quot;).append(&quot;&lt;option value=&#39;&quot;+value+&quot;&#39;&gt;&quot;+text+&quot;&lt;/option&gt;&
jQuery中的 $.extend() 和 $.fn.extend() ANGWH 于 2020-05-24 06:39:59 发布 注意:$.extend是为jQuery类添加添加类方法,用$.调用(类似$.ajax),$.fn.extend则是为jQuery对象添加方法(实例方法),用DOM元素
jquery 循环数组输出显示在html页面 jquery 没有双向数据绑定,但是很多需求确实需要我们从后台接收到数组或者对象循环显示在前台页面上,这时我们可以用字符串拼接,元素添加的方法去实现 js部分如下: 复制代码 $(function(){ var a=[&quot;1aa&quot;,&q
javascript事件委托理解,jQuery .on()方法一步到位实现事件委托 Javascript-概念原理 专栏收录该内容 10 篇文章0 订阅 订阅专栏 本篇文章借鉴自:博客园文章,只为自己巩固下事件委托方面的知识 概述: 什么叫事件委托?他还有一个名字叫做事件代理,(时间代理 事件委托,
JQuery-$.when().done().fail()的使用 原文引用于&#160;Echoo华地于&#160;2022-01-06 14:07:10 发布 jQuery的开发速度很快,几乎每半年一个大版本,每两个月一个小版本。 每个版本都会引入一些新功能。今天我想介绍的,就是从jQuery 1
jQuery tableExport导出 excel 上篇写的是jQuery&#160;导出word,就试试导出excel。看见网上写的很乱,我这就把我写的整理下来,有部分来自网上capy 1. js文件的引用 &lt;script type=&quot;text/javascript&quot;
jQuery的遍历-prev()和next()方法 &lt;div class=&quot;box&quot; id=&quot;box&quot;&gt; &lt;a href=&#39;#&#39; class=&quot;a&quot;&gt; &lt;input type=&quot;tex
attr()和addClass()的区别 方法 addClass() attr()用途&#x9;追加样式&#x9;设置样式对同一个网页元素操作&#x9;&lt;p&gt;test&lt;/p&gt;第1次使用方法&#x9;$(&quot;p&quot;).addClass(&quot;high&quot;);&#x9;$(&quot;p&
前端——函数(匿名函数、自执行函数) FreshLemon_ 于 2019-06-11 17:11:49 发布 函数声明:function box(){} 函数表达式:var box = function(){}; 匿名函数:function(){} (属于函数表达式) 1声明了一个函数: var
js: 获取标签元素data-*属性值的方法 彭世瑜 于 2022-05-23 09:59:50 发布 2165 收藏 1 文章标签: javascript 前端 jquery 版权 标签上有两个属性data-id 和 data-user-name, 需要通过js去获取 &lt;style&gt;
JavaScript函数详解:匿名函数、具名函数、函数传参、不定参、返回值、JS预解析机制 1.具名函数 定义: 调用: 方式1:方法名(); 可以多次调用 方式2:在事件中调用,直接写函数名,不需用括号 2.匿名函数 没有名字的函数 匿名函数在使用时只有两种情况: 1.匿名函数自执行:声明后不需要
如何等待ajax完成再执行相应操作 ajax广泛应用于异步请求,对于大多数业务来说,这是十分方便的,但对于一些特殊的业务,ajax的异步性会起到相反的作用。 例如在ajax请求成功后,后续的操作需要依赖ajax执行成功后的相应操作。 // 声明一个表示状态的全局变量 status var statu
一步一步教你写一个jQuery的插件教程(Plugin) 更新时间:2009年09月03日 02:10:54 作者: 我将会在下面的例子中一个一个的说明上面这几个条件,做完这些事情后我们就会创建一个高亮显示text的简单插件。 jQuery 的plugin开发需要注意的事情, 1. 明确jQuery