• Web开发(五)jQuery


    jQuery是什么

    <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的基础语法:$(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>jq选择器</title>
    </head>
    <body>
        <div class="header">this is in header</div>
        <div class="contenter">
            <p>this is in contenter p</p>
            <div class="left">
                <p id="left_p">left p</p>
            </div>
            <div class="medium">
                <p id="medium_p">medium p</p>
                <input type="text">
            </div>
            <div class="right">
                <p>right p</p>
            </div>
    
        </div>
        <div class="footer">this is in footer</div>
    
    </body>
    <script src="jquery-3.2.1.js"></script>
    <script>
    
    
        // 基本选择器
        // $('*').css('color','red') //通配选择器
        // $('#left_p').css('color','red') //id选择器
        // $('.contenter').css('color','red') //类选择器
        // $('p').css('color','red') //元素选择器
        // $('.header, .footer').css('color','red') //并集选择器
    
        // 层级选择器
        // $('.contenter p').css('color','red') //后代元素选择器
        // $('.contenter>p').css('color','red') //子元素选择器
        // $('.left+div').css('color','red')//后一个兄弟元素选择器
        // $('.left~div').css('color','red') //后所有兄弟元素选择器
    
        //基本筛选器
        // $('div:first').css('color','red')
        // $('div:last').css('color','red')
        // $('div:eq(-1)').css('color','red')
        // $('div:even').css('color','red')
        // $('div:gt(4)').css('color','red')
    
        //属性选择器
        // $('[id="left_p"]').css('color','red')
        // $('[id]').css('color','red')
        // $('[id*="t"]').css('color','red')
    
        //表单选择器
        // $('[type="text"]').css('width','500px')
        // $(':text').css('width','500px')
        
    </script>
    </html>
    View Code

    实例之左侧菜单

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>左侧菜单</title>
        <style>
            .menu{
                 200px;
                height: 600px;
                background-color: #bbffaa;
                float: left;
            }
            .title{
                color: red;
            }
            .item{
                padding-left: 15px;
            }
            .content{
                 1200px;
                height: 800px;
                background-color: fuchsia;
                float: left;
            }
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="menu">
            <div >
                <div class="title">导航网站</div>
                <div class="item ">
                    <p>导航一</p>
                    <p>导航二</p>
                    <p>导航三</p>
                </div>
            </div>
            <div>
                <div class="title">电影网站</div>
                <div class="item hide">
                    <p>电影一</p>
                    <p>电影二</p>
                    <p>电影三</p>
                </div>
            </div>
            <div>
                <div class="title">小说网站</div>
                <div class="item hide">
                    <p>小说一</p>
                    <p>小说二</p>
                    <p>小说三</p>
                </div>
            </div>
        </div>
        <div class="content"></div>
    </body>
    <script src="jquery-3.2.1.js"></script>
    <script>
        $('.menu .title').click(
            function () {
                $(this).next().removeClass('hide');
                $(this).parent().siblings().children('.item').addClass('hide')
            }
        )
    </script>
    </html>
    View Code

    实例之tab切换

    筛选器

    过滤筛选器

    $("li").eq(2)  $("li").first()  $("ul li").hasclass("test")

    查找筛选器

    $("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>
    </head>
    <body>
        <ul class="affair">
            <li class="eat">吃饭</li>
            <ol >
                <li>蛋白质</li>
                <li >膳食纤维</li>
                <li class="suger">糖类</li>
            </ol>
            <li class="learn">学习</li>
            <li>睡觉</li>
            <li>娱乐</li>
        </ul>
    
    </body>
    <script src="jquery-3.2.1.js"></script>
    <script>
        //过滤筛选器
        // $('li').eq(1).css('color','red')
        // $('li').first().css('color','red')
    
        //查找筛选器
        // $('ul').children('li').css('color','red') //children只选择子元素
        // $('ul').find('li').css('color','red') //find可以选择后代所有
    
        // $('.eat').next().css('color','red')
        // $('.eat').nextAll().css('color','red')
        // $('.eat').nextUntil('.learn').css('color','red') //不包括两端
    
        // $('.learn').prev().css('color','red')
        // $('.learn').prevAll().css('color','red')
        // $('.learn').prevUntil('.eat').css('color','red')
    
        // $('.suger').parent().css('color','red')
        // $('.suger').parents().css('color','red')
        // $('.suger').parentsUntil('.affair').css('color','red')  //不包括.affair
    
        $('.suger').siblings().css('color','red') //选择所有兄弟,不包括自己
    </script>
    </html>
    View Code

    操作元素

    属性操作

    attr用于自定义的属性,prop用于固有属性,比如对checkbox标签的checked属性进行操作推荐使用prop

    val用于固有属性的操作

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

    注意

    <body>
        <div class="div1" app="app1">div1</div>
        <input type="checkbox" checked="checked" apple="box1">box1
        <input type="checkbox">box2
    
        <script src="jquery-3.2.1.js"></script>
        <script>
            //判断是否属于某类
            console.log($('div').hasClass('div1')) //true
    
            //修改、获取属性值
            console.log($('div').attr("app")) //box1
            $('div').attr("app","app2")
            console.log($('div').attr('app')) //box2
    
            //固有属性推荐用prop,自定义属性推荐用attr
            console.log($(':checkbox:first').attr('checked')) //checked
            console.log($(':checkbox:last').attr('checked'))  //undefined
    
            console.log($(':checkbox:first').prop('checked')) //true
            console.log($(':checkbox:last').prop('checked'))  //false
    
    
        </script>
    </body>
    View Code

    jQuery的循环

    <body>
        <p>aa</p>
        <p>bb</p>
        <p>cc</p>
    <script src="jquery-3.2.1.js"></script>
    <script>
        ar1=[11, 22, 33]
    
        //jQuery循环方式一
        $.each(ar1, function (x,y) {
            console.log(x)
            console.log(y)
        })
        //jQuery循环方式二
        $('p').each(function () {
            console.log($(this))
        })
    
    </script>
    </body>
    <body>
        <form>
            <input type="checkbox" >睡觉
            <input type="checkbox">吃饭
            <input type="checkbox">学习
        </form>
        </br>
        <button onclick="selectall()">全选</button>
        <button onclick="selectreve()">反选</button>
        <button onclick="selectcancel()">取消</button>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
        function selectall(){
            $(':checkbox').each(function () {
                $(this).prop('checked',true)
            })
        }
    
        function selectcancel(){
            $(':checkbox').each(function () {
                $(this).prop('checked',false)
            })
        }
    
        function selectreve(){
            $(':checkbox').each(function () {
                if($(this).prop('checked')){
                    $(this).prop('checked',false)
                }
                else{
                    $(this).prop('checked',true)
                }
            })
        }
    
    </script>
    </body>
    实例-正反选

    文档处理

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

     实例之复制样式条

    <body>
        <div class="outer">
            <div class="item">
                <button onclick="add_obj(this)">+</button>
                <input>
            </div>
        </div>
    
    
    <script src="jquery-3.2.1.js"></script>
    <script>
        function add_obj(self) {
            //添加克隆的对象
            // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
            $clone_obj = $(self).parent().clone()
            $clone_obj.children('button').text('-').attr('onclick','del_obj(this)')
            $(self).parent().parent().append($clone_obj)
        }
    
        function del_obj(self) {
            //删除
            $(self).parent().remove()
        }
    </script>
    
    </body>
    View Code

     CSS操作

    CSS
            $("").css(name|pro|[,val|fn])
        位置
            $("").offset([coordinates])
            $("").position()
            $("").scrollTop([val])
            $("").scrollLeft([val])
        尺寸
            $("").height([val|fn])
            $("").width([val|fn])
            $("").innerHeight()
            $("").innerWidth()
            $("").outerHeight([soptions])
            $("").outerWidth([options])

    实例-返回顶部

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
                border: 0;
            }
            .div1{
                height:2000px;
                background-color: #bfa;
            }
            .returntop{
                background-color: beige;
                width:120px;
                height: 30px;
                position: fixed;
                bottom: 30px;
                right: 30px;
                text-align: center;
            }
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="div1"></div>
        <button class="returntop hide" onclick="returnTop()">return top</button>
        
    <script src="jquery-3.2.1.js"></script>
    <script>
        window.onscroll=function () {
            var cur_top = $(window).scrollTop()
            if (cur_top>300){
                $('.returntop').removeClass('hide')
            }else{
                $('.returntop').addClass('hide')
            }
        }
        function returnTop() {
            $(window).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>
        <style>
    
        </style>
    </head>
    <body>
        <div class="inter">
            <div class="div1">my website</div>
        </div>
        <button >addDiv</button>
    
    <script src="jquery-3.2.1.js"></script>
    <script>
    
        //事件绑定
        //弊端:这种绑定方式不会对手动添加的元素进行相应的事件绑定
        $('.inter div').bind('click', function () {
            alert('cheer up!')
        })
    
        //事件绑定
        //这是blind的一种简写方式
        $('button').click(function () {
            var $ele = $('<div><div>')
            $ele.text(111)
            $('.inter').append($ele)
        })
    
        //解除绑定
        $('.inter div').unbind('click')
    
    
        //事件委托
        //解决了blind带来的弊端
        $('.inter').on('click', 'div', function () {
            alert('cheer up!')
        })
    </script>
    </body>
    </html>
    事件委托和事件绑定
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div style="border: 1px solid #ddd; 600px;position: absolute;">
            <div id="title" style="background-color: black;height: 40px;color: white;">
                标题
            </div>
            <div style="height: 300px;">
                内容
            </div>
        </div>
    <script type="text/javascript" src="jquery-2.2.3.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>
    实例-面板拖动
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>bigger</title>
        <style>
            *{
                margin: 0;
                padding:0;
            }
            .outer{
                height: 350px;
                width: 350px;
                border: dashed 5px cornflowerblue;
            }
            .outer .small_box{
                position: relative;
            }
            .outer .small_box .float{
                height: 175px;
                width: 175px;
                background-color: darkgray;
                opacity: 0.4;
                fill-opacity: 0.4;
                position: absolute;
                display: none;
    
            }
    
            .outer .big_box{
                height: 400px;
                width: 400px;
                overflow: hidden;
                position:absolute;
                left: 360px;
                top: 0px;
                z-index: 1;
                border: 5px solid rebeccapurple;
                display: none;
    
    
            }
            .outer .big_box img{
                position: absolute;
                z-index: 5;
            }
    
    
        </style>
    </head>
    <body>
    
            <div class="outer">
                <div class="small_box">
                    <div class="float"></div>
                    <img src="small.jpg">
    
                </div>
                <div class="big_box">
                    <img src="big.jpg">
                </div>
    
            </div>
    
    
    <script src="jquery-2.1.4.min.js"></script>
    <script>
    
        $(function(){
    
              $(".small_box").mouseover(function(){
    
                  $(".float").css("display","block");
                  $(".big_box").css("display","block")
    
              });
              $(".small_box").mouseout(function(){
    
                  $(".float").css("display","none");
                  $(".big_box").css("display","none")
    
              });
    
              $(".small_box").mousemove(function(e){
    
                  var _event=e || window.event;
    
                  var float_width=$(".float").width();
                  var float_height=$(".float").height();
    
                  console.log(float_height,float_width);
    
                  var float_height_half=float_height/2;
                  var float_width_half=float_width/2;
                  console.log(float_height_half,float_width_half);
    
    
                   var small_box_width=$(".small_box").height();
                   var small_box_height=$(".small_box").width();
    
    
    
    //  鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
                  var mouse_left=_event.clientX-float_width_half;
                  var mouse_top=_event.clientY-float_height_half;
    
                  if(mouse_left<0){
                      mouse_left=0
                  }else if (mouse_left>small_box_width-float_width){
                      mouse_left=small_box_width-float_width
                  }
    
    
                  if(mouse_top<0){
                      mouse_top=0
                  }else if (mouse_top>small_box_height-float_height){
                      mouse_top=small_box_height-float_height
                  }
    
                   $(".float").css("left",mouse_left+"px");
                   $(".float").css("top",mouse_top+"px")
    
                   var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
                   var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);
    
                  console.log(percentX,percentY)
    
                   $(".big_box img").css("left", -percentX*mouse_left+"px")
                   $(".big_box img").css("top", -percentY*mouse_top+"px")
              })
        })
    
    
    </script>
    </body>
    </html>
    实例-放大镜

    动画效果

    隐藏显示

    用于切换被选元素的 hide() 与 show() 方法。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-2.1.4.min.js"></script>
        <script>
    
    $(document).ready(function() {
        $("#hide").click(function () {
            $("p").hide(1000);
        });
        $("#show").click(function () {
            $("p").show(1000);
        });
    
    //用于切换被选元素的 hide() 与 show() 方法。
        $("#toggle").click(function () {
            $("p").toggle();
        });
    })
    
        </script>
        <link type="text/css" rel="stylesheet" href="style.css">
    </head>
    <body>
    
    
        <p>hello</p>
        <button id="hide">隐藏</button>
        <button id="show">显示</button>
        <button id="toggle">切换</button>
    
    </body>
    </html>
    View Code

    滑动

    slideDown slideUp  slideToggle

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-2.1.4.min.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">helloworld</div>
    
    </body>
    </html>
    View Code

    淡入淡出

    fadein  fadeout  fadetoggle  fadeto

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-2.1.4.min.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;  80px;height: 80px;background-color: blueviolet"></div>
    
    </body>
    </html>
    View Code

    回调函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-2.1.4.min.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>
    View Code

     扩展方法 (插件机制)

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

    参考

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

    博客园https://www.cnblogs.com/yuanchenqi/articles/6070667.html

  • 相关阅读:
    git如何将一个远程仓库的某个分支拉取到当前分支?
    linux下如何检查内核补丁是否符合社区代码规范?
    javascript快速入门20--Cookie
    javascript快速入门19--定位
    javascript快速入门18--样式
    javascript快速入门17--事件
    javascript快速入门16--表格
    javascript快速入门15--表单
    javascript快速入门15--节点
    javascript快速入门14--DOM基础
  • 原文地址:https://www.cnblogs.com/dreamer-lin/p/11743683.html
Copyright © 2020-2023  润新知