jquery

 

一 jQuery是什么? 

 

                      

从javascript语言诞生开始,大量的开发人员使用js来完成页面特效,于是有些人就把自己工作中常用的代码段进行封装成函数或者函数库(工具库)并开源给所有开发者使用。所以javascript语言中拥有非常多,优秀的工具库。
目前全世界范围内使用最广泛的javascript函数库主要有:jQuery,Vue.js。
其中jQuery是2006年发布的工具库,jQuery简单易用,可以让开发者大量节省使用javscript开发特效的代码。
jquery 简称jQ,写jq代码,本质上就是写js代码。如果以后jQuery代码无法完成的事情,还是会使用js。
jquery的标语 Write Less, Do More(写得少,做得多)
有了它,可以用更少的js代码做更多事情。
官方网站: http://jquery.com/
[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还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。
 

1-jQuery的版本
  1.x 系列 兼容低版本的浏览器
  2.x 系列 放弃支持低版本浏览器
  3.x 系列 放弃支持低版本浏览器

2-获取jQuery库
  下载地址:https://code.jquery.com/
  下载回来的jQuery版本文件有两个格式:
    jquery-1.12.4.js 未压缩文件(uncompressed) 适用于开发和学习
    jquery-1.12.4.min.js 压缩文件(minified) 适用于项目线上运营

3-在HTML网页中引入jQuery
  jQuery本质上就是一个装满了javascript函数的文件,所以引入jQuery,还是使用script标签即可。
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 把预先下载的jQuery库文件保存在项目根目录下js目录中 -->
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<script>
    // 通过在终端打印$(美元符),可以判断 jQuery是否成功引入到当前网页中。
    console.log( $ );
</script>
</body>
</html>
导入方式和判断是否导入成功

 

4- $的介绍
  jQuery提供了大量的javascript操作函数给开发者使用,这些操作函数全部都被封装到了`jQuery`对象中了。
  而`$`则是jQuery的核心对象`jQuery`对象的缩写,开发中我们都会使用`$`来调用jQuery库提供的工具方法来完成特效。

总结:

  1. jQuery目前我们使用1.x版本,
  2. jQuery本质就是js本件,在HTML网页通过script标签的src属性来引入。
  3. $是jQ的核心对象jQuery的简写,开发中一般通过$来调用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 对象, 那么要在变量前面加上$.
  
  
dom对象和jquery对象的转换 
    var $variable = jQuery 对象 = $()  //Jquery是一个集合   当只有一个元素时[dom01,]
    var variable = DOM 对象  //1:只用一个元素 id 方式:document.getElementById(" test ") 2:document.getElementsByClassName(“类名”)# dom对象集合:  [dom对象,dom对象2,...]
     
      $()[0]         $variable[0]:jquery对象转为dom对象      $("#msg").html(); $("#msg")[0].innerHTML
  $(".c1")----------------->DOM对象
         <-----------------
      $(DOM) # [DOM,] 
 
document.getElementsByClassName("c1")  # [dom,dom2,...]
$(".c1") # [dom,dom2,]   
  集合类型:
         1 元素一定是DOM对象
         2 提供了更多的方法

 

  

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

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

 

【掌握】jQuery入口函数

让js代码可以在页面加载完成以后执行,在之前的学习中我们需要使用window.onload来完成。
在jQuery中,也提供了一个类似的页面加载函数给我们使用。这个函数在jQuery中也称之为"入口函数"。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
    <script>
        // window.onload = function(){
        //     console.log ( document.getElementById("title").innerHTML );
        // };
        // window.onload = function(){
        //     console.log(111);
        // }

        // 上面的代码只有最后一个onload里面的代码会被执行,前面的已经被覆盖了,
        // 在jQuery中可以使用ready入口函数来解决这个问题,ready入口函数可以使用多次,
        // $(document).ready(function(){
        //     console.log( document.getElementById("title").innerHTML );
        // });
        //
        // $(document).ready(function(){
        //     console.log("ready");
        // });


        // 上面的ready函数写法可以简化
        $(function(){
            console.log( document.getElementById("title").innerHTML );
        });

        $(function(){
            console.log("ready");
        });

        $(function(){
            // 这里编写我们的js/jQuery代码
        });
    </script>
</head>
<body>
    <h1 id="title">标题</h1>
</body>
</html>
入口函数例子

和window.onload的区别

$(function(){}) 和window.onload = function(){} 有点像,但是jq的页面加载函数一个js可以出现很多次,都会被执行(但一般也不会这么写),而如果window.onload在同一个js文件中出现两次或者以上,则只会执行最后一个。
总结:
1. 入口函数,声明格式:
  $(function(){
    // 编写js/jQ代码
  });

2. jQuery的入口函数就是用来替换window.onload=function(){};
  1. 代码更简短
  2. window.onload只能一次,而$(function(){});可以使用多次。

 

 

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

3.1   选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<p id="first">一个文本</p>

<script>
    // jQuery参照了css操作元素外观的选择器写法,自己内部实现了一套获取js元素的选择器功能,
    // 这套功能的使用,我们完全可以向之前学习css那样来使用这要选择器功能,
    // jQuery还额外提供了一些css本来没有的选择器

    // document.getElementById()  根据id属性值获取一个元素
    // $("#id值")
    console.log( $("#first") );

    // 通过id元素获取元素的内容
    // js写法
    let f = document.getElementById("first");
    console.log( f.innerHTML );

    // jQuery写法,下面代码就是上面2行代码的缩写
    console.log( $("#first").html() );

    // 细节:$()函数获取到的元素,返回值是一个类数组的jQuery对象,并非js那样的一个元素对象
    // 这个类数组的jQuery对象拥有数组的操作方法,但是并不具备js元素的操作方法
    // 例如:
    console.log( $("#first").innerHTML ); // 这里根本无法获取内容
</script>
</body>
</html>
选择器概述

3.1.1 基本选择器      

1
$("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
//ID选择器
<p id="first">一个文本</p>
<script>
    // jQuery参照了css操作元素外观的选择器写法,自己内部实现了一套获取js元素的选择器功能,
    // 这套功能的使用,我们完全可以向之前学习css那样来使用这要选择器功能,
    // jQuery还额外提供了一些css本来没有的选择器

    // document.getElementById()  根据id属性值获取一个元素
    // $("#id值")
    console.log( $("#first") );

    // 通过id元素获取元素的内容
    // js写法
    let f = document.getElementById("first");
    console.log( f.innerHTML );

    // jQuery写法,下面代码就是上面2行代码的缩写
    console.log( $("#first").html() );

    // 细节:$()函数获取到的元素,返回值是一个类数组的jQuery对象,并非js那样的一个元素对象
    // 这个类数组的jQuery对象拥有数组的操作方法,但是并不具备js元素的操作方法
    // 例如:
    //console.log( $("#first").innerHTML ); // 这里根本无法获取内容
</script>



//类选择器
<ul class="list">
    <li class="num1">第1个列表</li>
    <li class="num2">第2个列表</li>
    <li class="num2">第3个列表</li>
</ul>
<script>
    // 获取类元素
    // document.getElementsByClassName("类名")
    // $(".类名")

    //console.log( $(".list") ); //获取类数组的jQuery对象
    //console.log( $(".list").html() );

    // 可以获取多个类元素
    //console.log( $(".num2") );

    // 注意了,如果jQuery对象获取的是多个元素,那么获取内容的时候只会显示第一个成员的内容
    //console.log( $(".num2").html() );

    // 所以如果要获取这些元素所有的内容,则使用数组的遍历即可
    //for(let i = 0;i<$(".num2").length;i++){
     //    console.log( $(".num2").eq(i).html() ); // $(".num2")[i] 在jQuery中可以使用 $(".num2").eq(i)
     //}
</script>


//标签选择器
<div class="list2">
    <p class="num3">第1个列表</p>
    <p class="num4">第2个列表</p>
    <p class="num4">第3个列表</p>
</div>
<p class="num4">第4个列表</p>

<script>
    // 使用标签名选择器
   // console.log( $("div") );

    // 更多的是用使用层级选择器
    //console.log( $(".list2 .num3") );
    //console.log( $(".list2 .num4") );
</script>


//属性选择器
<style>
    input[name=idcard]{
       border:1px solid red;
    }
</style>
<input type="text" name="uname">
<input type="text" name="address">
<input type="text" name="idcard">
<script>
    // 属性选择器
    console.log( $("input") );
    console.log( $("input[name=idcard]") );
</script>

</body>
</html>
基本选择器例子

3.1.2 层级选择器   

1
$(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")

3.1.3 基本筛选器  

1
$("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")

3.1.4 属性选择器

1
$('[id="div1"]')   $('["alex="sb"][id]')

3.1.5 表单选择器      

1
$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>


</head>
<body>


<div class="c1">
    <div class="c2">234</div>
    <p>345</p>
    <div>
        <span>678</span>
        <a href="" id="i1" class="c1">789</a>
        <p class="c2">666</p>
    </div>
    <ul class="c2">
        <li class="c3">111</li>
        <li class="c3">111</li>
        <li class="c3">111</li>
        <li class="c3 end">111</li>
        <li class="c3">111</li>
    </ul>

</div>

<div class="c2">999</div>



<p class="c4" alex="xxx">alex</p>
<p class="c4" alex="yyy">alex2</p>
<p class="c5" alex="yyy">egon</p>


<input type="text">
<input type="password">


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

<script>
   // 基本选择器
   // $(".c2").css("color","red")
   // $(".c1 *").css("color","red")
   // $("span").css("color","red")
   // $("#i1").css("color","red");

    // 层级选择器
    // $(".c1 .c2,.c1 span").css("color","red")
    // $(".c1>.c2").css("color","red")

    // 基本筛选器
    // $(".c2 .c3").css("color","red")
    // $(".c2 .c3:first").css("color","red");
    // $(".c2 .c3:last").css("color","red");

   // $(".c2 .c3:eq(3)").css("color","red");  //下标索引 为3(0,1,2,3....)的标签标红
    // $(".c2 .c3:even").css("color","red");  //下标索引 为偶数时(0,1,2,3....)的标签标红
    // $(".c2 .c3:odd").css("color","red");  //下标索引 为奇数时(0,1,2,3....)的标签标红
    // $(".c2 .c3:gt(1)").css("color","red"); //下标索引 大于1的  标签标红
    // $(".c2 .c3:lt(3)").css("color","red");//下标索引 小于3的  标签标红

     //  属性选择器

   // $("[alex='xxx']").css("color","red");
   // $("[alex='yyy'][class='c4']").css("color","red");  //两个属性都满足的标红

   //  表单选择器
    // $("[type='text']").css("border","red solid 1px");
     //$(":password").css("border","red solid 1px")

    //  筛选器
    // $(".c2 .c3").eq(3).css("color","red");
    // $(".c2 .c3").first().css("color","red");//第一个
    // $(".c2 .c3").last().css("color","red");//最后一个
    // $(".c2 .c3").gt(3).css("color","red");
    //$("#i1").hasClass("c1")   //console.log($("#i1").hasClass("c1"));  判断id = "i1"这个标签里面是否有c1类

    //  导航查找
      // 查找兄弟标签
      // [dom1,dom2,dom3,dom4,dom5]---->[dom2]------>[dom3,]
       // next
      // $(".c2 .c3").eq(1).next().css("color","red");  //找索引为1的下一个标签
     // $(".c2 .c3").eq(1).nextAll().css("color","red"); //找索引为1以后所的有标签
      // $(".c2 .c3").eq(1).nextUntil(".end").css("color","red");//  找索引为1以后所的有标签 直到遇到有end类的标签结束  开区间  取不到带end类的标签
        $(".c2 .c3").eq(3).prev().css("color","red"); //找索引为3的上一个标签
       // $(".c2 .c3").eq(3).prevAll().css("color","red");//跟上面差不多
       //$(".c2 .c3").eq(3).prevUntil(".end").css("color","red");//跟上面差不多
        //$(".c2 .c3").eq(3).siblings().css("color","red");  //所有的兄弟标签

       // 查找父亲
       // [c2,]----->[c1,]
       // $(".end").parent().parent();
       // $(".end").parents();  //   [.c2,.c1,.body]

      // 查找后代
      //  $(".c1").children(".c2").css("color","red"); // 儿子层
      //  $(".c1").find(".c2").css("color","red");   // 后代层


</script>
</body>
</html>
寻找元素(选择器和筛选器) 例子
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<ul class="list">
    <li>0</li>  <!-- 索引下标从0开始 -->
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
<script>
    // $(".list li") // 获取所有.list下面的li
    console.log( $(".list li:odd") ); // 获取所有.list下面的索引下标为奇数的li
    console.log( $(".list li:even") );

    // 深入学习,实现一个换色效果
    // .css()   给jQuery元素添加css外观
    $(".list li:odd").css({
        // "color":"red",
        color:"red", // 对象的属性也可以是没有引号的
        // "background-color":"gray"
        backgroundColor:"gray", // 如果样式属性是多个单词组成的,那么不要引号的话就要改成驼峰式
    });
</script>

<ul>
    <li><input type="checkbox" checked></li>
    <li><input type="checkbox"></li>
    <li><input type="checkbox" checked></li>
    <li><input type="checkbox"></li>
</ul>
<script>
    // 获取多选框中具有勾选状态的所有标签,一般用于完成反选,全选或者全不选
    console.log( $("li input:checked") );
</script>
</body>
</html>
寻找元素(选择器和筛选器) 例子 02
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<ul class="list">
    <li>1</li>
    <li class="last num">2</li>
    <li class="last">3</li>
    <li class="last num"></li>
</ul>
<script>
    // 获取所有元素li中的第二个[索引下标为1]
    console.log( $(".list li") );
    console.log( $(".list li").eq(1) ); // eq表示从查询结果的数组提取指定下标的成员

    // 获取除了指定元素意外的所有其他li元素
    // not() 表示排除指定选择器对应的元素,提取结果中的其他元素
    console.log( $(".list li").not(".last") );

    // 在所有li.last元素中找出内部具有.num类名的元素
    // has() 表示从结果中提取具有指定选择器对应的元素出来
    // console.log( $(".list .last").has(".num") );  // 这里.last和.num是同一个级别,同一个元素了。所以无法获取
</script>
<ul class="list2">
    <li><a href="">第0个</a></li>
    <li><a class="link" href="">第1个</a></li>
    <li><a href="">第2个</a></li>
    <li><a class="link" href="">第3个</a></li>
    <li><a href="">第4个</a></li>
</ul>
<script>
    // 在所有li元素中找出内部具有.link类名的元素
    // 可以使用has
    console.log( $(".list2 li").has(".link") ); // 注意,这里是返回元素
</script>
</body>
</html>
寻找元素(选择器和筛选器) 例子 03

 

3.1.6 表单属性选择器

    :enabled
    :disabled
    :checked
    :selected
<body>

<form>
    <input type="checkbox" value="123" checked>
    <input type="checkbox" value="456" checked>


  <select>
      <option value="1">Flowers</option>
      <option value="2" selected="selected">Gardens</option>
      <option value="3" selected="selected">Trees</option>
      <option value="3" selected="selected">Trees</option>
  </select>
</form>


<script src="jquery.min.js"></script>
<script>
    // console.log($("input:checked").length);     // 2

    // console.log($("option:selected").length);   // 只能默认选中一个,所以只能lenth:1

    $("input:checked").each(function(){

        console.log($(this).val())
    })

</script>


</body>
View Code

 

3.2 筛选器

3.2.1  过滤筛选器    

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

3.2.2  查找筛选器  

 查找子标签:         $("div").children(".test")      $("div").find(".test")  
                               
 向下查找兄弟标签:    $(".test").next()               $(".test").nextAll()     
$(".test").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="js/jquery-1.12.4.js"></script>
</head>
<body>

<p>第1个文本</p>
<p class="p2">第2个文本</p>
<div class="box">
    <p class="p3">第3个文本</p>
    <a href="">链接</a>
</div>
<a href="">链接</a>

<script>
    // 获取div所有的兄弟元素
    // siblings 获取当前元素的所有兄弟元素
    console.log( $(".box").siblings() );

    // 获取div元素前面的所有兄弟元素
    // prevAll()
    console.log( $(".box").prevAll() );

    // 获取div元素后面的所有兄弟元素
    // nextAll()
    console.log( $(".box").nextAll() );

    // 获取div元素前面的一个兄弟元素
    console.log( $(".box").prev() );

    // 获取div元素后面的一个兄弟元素
    // next() 下一个元素
    // next().next() 下2个元素
    console.log( $(".box").next() );

    // 获取当前元素自身下标,可以使用index();
    console.log( $(".box").index() );

</script>
</body>
</html>
查找筛选器例子01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<p>第1个文本</p>
<p class="p2">第2个文本</p>
<div class="box">
    <p class="p3">第3个文本
        <span>
            <a href="" class="move"></a>
        </span>
    </p>
    <a href="">链接</a>
</div>
<a href="">链接</a>
<script>
    // 获取指定元素的父元素
    // parent()
    console.log( $(".box").parent() );
    console.log( $(".p3").parent().parent() );

    // 获取指定元素的父系元素[爸爸、爷爷、太爷、祖宗]
    console.log( $(".p3").parents() );

    // 获取指定元素的所有子元素 注:只到儿子一级
    console.log( $("body").children() );

    // 获取指定元素的所有孙子元素 注:只到孙子一级
    console.log( $("body").children().children() );

    // 通过.box获取内部的.move标签
    // find 查找具有指定选择器的子孙元素
    console.log( $(".box").find(".move") );
</script>
</body>
</html>
查找筛选器例子02

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

4.1 事件

页面载入

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

事件绑定

//语法:  标签对象.事件(函数)    
eg: $("p").click(function(){})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<ul>
    <li>123</li>
    <li>234</li>
    <li>345</li>
    <li>567</li>
</ul>

<script src="jquery.js"></script>
<script>
    /*
    var eles=document.getElementsByTagName("li"); //[dom对象数组]

    for(var i=0;i<eles.length;i++){
        eles[i].onclick=function () {
            alert(this.innerHTML)
            console.log(this)
        }
    }
    */

    $("ul li").click(function () {
       //  alert(this.innerHTML)
      // this: 当前触发DOM
      console.log(this)  //打印dom对象(一个HTML标签)
      console.log($(this))  //打印 jquery对象集合  不过这个集合只有一个值
       alert($(this).html())
    })




</script>
</body>
</html>
事件绑定的例子
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .left,.right{
            float: left;
            height: 750px;
        }

        .left{
            width: 20%;
            background-color: lightblue;
        }
        .right{
            width: 80%;
            background-color: lightgray;
        }

        .item{
            padding: 15px;
        }

        .item .title{
            text-align: center;
            background-color: goldenrod;
        }

        .hide{
            display: none;
        }

    </style>
</head>
<body>



<div class="outer">
    <div class="left">
         <div class="item">
             <div class="title">菜单一</div>
             <div class="con">
                 <p>111</p>
                 <p>111</p>
                 <p>111</p>
             </div>
         </div>
         <div class="item">
             <div class="title">菜单二</div>
             <div class="con hide">
                 <p>111</p>
                 <p>111</p>
                 <p>111</p>
             </div>
         </div>
         <div class="item">
             <div class="title">菜单三</div>
             <div class="con hide">
                 <p>111</p>
                 <p>111</p>
                 <p>111</p>
             </div>
         </div>
    </div>
    <div class="right">

    </div>
</div>


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

<script>

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

        // 显示点击菜单的内容标签
        // $(this).next().removeClass("hide");
        //  [.title]------>[.item]----->[.item,.item]----->[.con,.con]
        // $(this).parent().siblings().children(".con").addClass("hide");

        // jquery支持链式操作
        $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");
 
    })
</script>
</body>
</html>
jQuery菜单栏

 

事件委派:

$("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。
复制代码
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<hr>
<button id="add_li">Add_li</button>
<button id="off">off</button>

<script src="jquery.min.js"></script>
<script>
    $("ul li").click(function(){
        alert(123)
    });

    $("#add_li").click(function(){
        var $ele=$("<li>");
        $ele.text(Math.round(Math.random()*10));
        $("ul").append($ele)

    });


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

     $("#off").click(function(){
         $("ul li").off()
     })
    
</script>
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

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

       $(function () {
                    $(".add").click(function () {
                          $("ul").append("<li>456</li>")
                      });

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

                      //  事件委派   因为html从上到下加载  新创建的HTML标签(没有被加载) 只能通过父级标签委派 才能找到这个新建的标签(即子标签)

                     $("ul").on("click","li",function () {
                          console.log(this)
                      })
       });

      $(document).ready(function () { });  //script要放在body之后    否则就加  $(document).ready(function () { });   因为加载顺序







</script>
</head>
<body>

<ul>
    <li>123</li>
    <li>234</li>
    <li>345</li>
</ul>


<button class="add">ADD</button>



</body>
</html>
事件委派例子

 

事件切换

hover事件:

一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。

over:鼠标移到元素上要触发的函数

out:鼠标移出元素要触发的函数

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .test{

            width: 200px;
            height: 200px;
            background-color: wheat;

        }
    </style>
</head>
<body>


<div class="test"></div>
</body>
<script src="jquery.min.js"></script>
<script>
//    function enter(){
//        console.log("enter")
//    }
//    function out(){
//        console.log("out")
//    }
// $(".test").hover(enter,out)


$(".test").mouseenter(function(){
        console.log("enter")
});

$(".test").mouseleave(function(){
        console.log("leave")
    });

</script>
</html>
复制代码

4.2 属性操作

--------------------------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>
</head>
<body>
<p class="c1">234</p>



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


<script>

     $(".c1").html("<a href=''>666</a>");//设置文本内容 可以插入一个标签
      console.log($(".c1").html()); //获取文本内容
      console.log($(".c1").test()); //获取文本内容
     // $(".c1").text("<a>666</a>");//设置文本内容  只能写文本

</script>

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

<input type="text" class="c1" value="alex">
<textarea class="c2" name="" id="" cols="30" rows="10">egon</textarea>
<select name="" id="s1">
    <option value="1">111</option>
    <option value="2" selected>222</option>
    <option value="3">333</option>
</select>



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


<script>
   // 取值操作
   console.log($(".c1").val());
   console.log($(".c2").val());
   console.log($("#s1").val());
   // 赋值操作
    $(".c1").val("123");
    $(".c2").val("456");
    $("#s1").val("3");

</script>

</body>
</html>
value/val值操作
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<div class="c1" id="i1" alex="xxx">alex</div>


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


<script>
   console.log($(".c1").attr("id")); //获取属性id的值
   console.log($(".c1").attr("class"));//获取属性class的值
   console.log($(".c1").attr("alex"));//获取属性alex的值

   $(".c1").attr("id","i2"); //设置id的值
   $(".c1").attr("alex","yyy");
   $(".c1").removeAttr("alex")//删除属性

</script>

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

    <style>
        .c1{
            color: red;
        }

        .c2{
            background-color: green;
        }
        .c3{
            font-size: 45px;
        }
    </style>
</head>
<body>


<div class="c1 c2" >alex</div>
<script src="jquery.js"></script>


<script>
     //$(".c2").addClass('c3');   //给所有c2类的jquery对象添加类c3
    // $(".c2").removeClass("c1"); //删除所有c2类的jquery对象的类c1
    $(".c2").removeAttr("class")//删除class类属性
</script>

</body>
</html>
class属性操作
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
    <img src="images/1.png" alt="">
    <p>第1个文本</p>
    <form action="">
        账号:<input type="text" value="admin"><br>
        密码:<input type="password" name="password" ><br>
        爱好:<input type="checkbox" name="love" value="qq">qq
              <input type="checkbox" name="love" value="bb">bb
              <input type="checkbox" name="love" value="ww">ww
    </form>

    <script>
        // 获取元素指定属性的值
        // 通过attr来获取元素指定属性的值
        console.log( $("img").attr("src") );

        // 设置元素指定属性的值[设置单个属性值]
        $("img").attr("src","images/2.png");

        // 设置多个属性值
        // 参数是json对象,{键1:值,键2:值....}
        $("img").attr({"src":"2.png","alt":"这是一张图片"})

        // 还可以在修改属性的时候,传入匿名函数[扩展]
        $("img").attr("src",function(){
            let num = parseInt(Math.random()*2+1);
            return "images/"+num+".png";
        });

        // 针对在html元素中,有些元素的属性和值是同名的.
        // checked="checked"
        // selected="selected"
        // disabled="disabled"
        // 在js中修改状态都可以使用布尔值来处理
        $("input[name=love]").attr("checked",false);
    </script>
</body>
</html>
属性操作2
<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>
属性操作3--HTML元素本身就带有的固有属性,在处理时,使用prop方法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.4.js"></script>
    <style>
    .first {
        color: red;
        font-size: 32px;
    }
    .last{
        border: 1px solid blue;
        background-color: orange;
    }
    .bg{
        background-color: #aaaaaa;
    }
    </style>
</head>
<body>

<ul>
    <li class="first">第1</li>
    <li>第2</li>
    <li>第3</li>
</ul>

    <script>
    // css()
    // 获取元素的指定样式
    console.log( $(".first").css("color") );
    console.log( $(".first").css("font-size") );

    // 设置元素的指定样式[一个样式]
    $(".first").css("background-color","pink");
    // 设置多个样式
    $(".first").next().css({
        "background-color":"yellow",
        "border":"1px solid red",
    });

    // 针对一次性设置多个样式的情况,jQuery还提供了 addClass 和 removeClass给我们使用。
    // eq(-1) 表示倒数,只有在jQuery中支持
    $("ul li").eq(-1).addClass("last");

    // 移除类名
    $("ul li").eq(0).removeClass("first");
    </script>


    <button class="btn">开灯</button>
    <script>
        $(".btn").click(function(){
            // 执行toggleClass的时候,当前元素如果有对应的类名,则被删除
            // 如果没有,则自动添加
            $("body").toggleClass("bg");
        });
    </script>
</body>
</html>
类与css的属性操作

 

 

 

4.3 each循环

我们知道,

1
$("p").css("color","red")  

是将css操作加到所有的标签上,内部维持一个循环;但如果对于选中标签进行不同处理,这时就需要对所有标签数组进行循环遍历啦

jquery支持两种循环方式:

方式一

格式:$.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())
})

其中,$(this)代指当前循环标签。

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

<ul>
    <li>123</li>
    <li>234</li>
    <li>345</li>
</ul>


<script src="jquery.js"></script>
<script>
   //  用法1:循环序列数据
    var arr=[111,222,333];
    $.each(arr,function (i,j) {
        // 循环体
        if(j===222){
           // return  -123  // 类似continue
           return false  // break
        }
        console.log(i,j)

    });

    var obj={"name":"alex","age":123};
    $.each(obj,function (i,j) {
       // 循环体
        console.log(i,j)
    });

    // 方法2:  循环dom对象
    $("ul li").each(function () {
        //  this: 循环体中this代指的当前循环的标签:dom对象
        console.log(this);
        $(this).html($(this).html()+"yuan")
    })



</script>

</body>
</html>
each循环例子

each扩展

/*
        function f(){

        for(var i=0;i<4;i++){

            if (i==2){
                return
            }
            console.log(i)
        }

    }
    f();  // 这个例子大家应该不会有问题吧!!!
//-----------------------------------------------------------------------


    li=[11,22,33,44];
    $.each(li,function(i,v){

        if (v==33){
                return ;   //  ===试一试 return false会怎样?
            }
            console.log(v)
    });

//------------------------------------------


    // 大家再考虑: function里的return只是结束了当前的函数,并不会影响后面函数的执行

    //本来这样没问题,但因为我们的需求里有很多这样的情况:我们不管循环到第几个函数时,一旦return了,
    //希望后面的函数也不再执行了!基于此,jquery在$.each里又加了一步:
         for(var i in obj){

             ret=func(i,obj[i]) ;
             if(ret==false){
                 return ;
             }

         }
    // 这样就很灵活了:
    // <1>如果你想return后下面循环函数继续执行,那么就直接写return或return true
    // <2>如果你不想return后下面循环函数继续执行,那么就直接写return false


// ---------------------------------------------------------------------
View Code

 

4.4 文档节点处理

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


<h3>welcom to learn JS</h3>
<div class="c1">

    <p class="c3">123</p>

</div>

<div class="c2">
    <img id="img" width="300" height="300" src="http://img0.imgtn.bdimg.com/it/u=2777233881,1106483217&fm=26&gp=0.jpg" alt="">
</div>
<hr>
<button class="add">ADD</button>
<button class="remove">remove</button>
<button class="replace">replace</button>
<script src="jquery.js"></script>
<script>
    // 创建添加节点
    $(".add").click(function () {
        // 创建节点
        var $ele=$("<p>");
        $ele.html("234");   // $ele=$("<p>234</p>");
        // 添加节点
        //$(".c1").append($ele)
        $(".c1").append("<p>666</p>");
        $("<p>666</p>").appendTo(".c1");
        $(".c1").after("<p>666</p>");
    });

    // 删除节点
    $(".remove").click(function () {
        $(".c2 img").remove()
    });

    // 替换节点
    $(".replace").click(function () {
        $(".c1 .c3").replaceWith("<h1>Hello</h1>")
    })



</script>

</body>
</html>
jQuery的节点操作

 

4.5 动画效果

显示隐藏

复制代码
<!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>
复制代码

滑动

<!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>
滑动:slideDown,slideUp,slideToggle,
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>层级菜单</title>    
    <style type="text/css">
        body{
            font-family:'Microsoft Yahei';
        }
        body,ul{
            margin:0px;
            padding:0px;
        }
        
        ul{list-style:none;}


        .menu{
            width:200px;
            margin:20px auto 0;
            /*margin: 0 auto; 居中*/
        }

        .menu .level1,.menu li ul a{
            display:block;
            width:200px;
            height:30px;
            line-height:30px;
            text-decoration:none; /* text-decoration 属性用来设置或删除文本的装饰。主要是用来删除链接的下划线*/
            background-color:#3366cc;
            color:#fff;
            font-size:16px;
            text-indent:10px;            
        }

        .menu .level1{
            border-bottom:1px solid #afc6f6;  /*底边框 1像素 #afc6f6 颜色*/
            
        }

        .menu li ul a{
            font-size:14px;
            text-indent:20px; /*text-indent: 150px;      首行缩进150px*/
            background-color:#7aa1ef;
                    
        }

        .menu li ul li{
            border-bottom:1px solid #afc6f6;
        }

        

        .menu li ul{
            display:none;
        }  /* 隐藏所有的ul标签 */

        .menu li ul.current{
            display:block;
        } /* 显示ul.current标签 */

        .menu li ul li a:hover{
            background-color:#f6b544;
        } /* a:hover(鼠标放在链接上的状态),用于产生视觉效果。 颜色#f6b544 */


    </style>
    
    <script src="js/jquery-1.12.4.js"></script>
    <script type="text/javascript">
    $(function(){
        // 单击一级菜单,显示隐藏 滑动 二级菜单
        $('.level1').click(function(){
            $(this).next().slideDown().parent().siblings().children('ul').slideUp()
            /*$(this).next().slideDown()  滑出来 显示*/
            /*$(this).next().parent().siblings().children('ul').slideUp()  滑进去 隐藏*/
        })
    })
    </script>
</head>
<body>
    <ul class="menu">
        <li>
            <a href="#" class="level1">手机</a>
            <ul class="current">
                <li><a href="#">iPhone X 256G</a></li>
                <li><a href="#">红米4A 全网通</a></li>
                <li><a href="#">HUAWEI Mate10</a></li>
                <li><a href="#">vivo X20A 4GB</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="level1">笔记本</a>
            <ul>
                <li><a href="#">MacBook Pro</a></li>
                <li><a href="#">ThinkPad</a></li>
                <li><a href="#">外星人(Alienware)</a></li>
                <li><a href="#">惠普(HP)薄锐ENVY</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="level1">电视</a>
            <ul>
                <li><a href="#">海信(hisense)</a></li>
                <li><a href="#">长虹(CHANGHONG)</a></li>
                <li><a href="#">TCL彩电L65E5800A</a></li>                
            </ul>
        </li>
        <li>
            <a href="#" class="level1">鞋子</a>
            <ul>
                <li><a href="#">新百伦</a></li>
                <li><a href="#">adidas</a></li>
                <li><a href="#">特步</a></li>
                <li><a href="#">安踏</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="level1">玩具</a>
            <ul>
                <li><a href="#">乐高</a></li>
                <li><a href="#">费雪</a></li>
                <li><a href="#">铭塔</a></li>
                <li><a href="#">贝恩斯</a></li>
            </ul>
        </li>
        
    </ul>
</body>
</html>
层级菜单:利用滑动函数实现

 

淡入淡出

复制代码
<!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; 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-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>
复制代码

菜单栏展开与隐藏

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

    <style>
        .box{
            margin: 100px auto;              /*margin:25px;  所有的4个边距都是25px        margin: 0 auto; 居中 */
            width: 70%;
        }
        ul{
            list-style: none;  /*list-style: none 设置列表标记的 默认会是实心圆点 设成none就是没有标记*/
            background-color: grey;
            line-height: 40px;


        }
        ul li{
            display: inline-block;
            width: 100px;
            height: 40px;
            text-align: center;

        }

        .content{
            margin-top: -15px;
        } /* ul 和 div 之间有空隙*/

        .content div{
            height: 300px;
            background-color: beige;
        }

        .active{
            background-color: #e4393c;
            color: white;
        }
        .hide{
            display: none;
        }


    </style>
</head>
<body>

<div class="box">

    <ul>
        <li rel="intro" class="active">商品介绍</li>
        <li rel="after_sale">售后保障</li>
        <li rel="comment">商品评价</li>
    </ul>

    <div class="content">
        <div class="intro">
              商品介绍......
        </div>
        <div class="after_sale hide">
              售后保障.....
        </div>
        <div class="comment hide">
              商品评价....
        </div>
    </div>
</div>


<script src="js/jquery-1.12.4.js"></script>
<!--<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>-->

<script>
    // JS版本
    /*
    let lis=document.getElementsByTagName("li");
    for(var i=0;i<lis.length;i++){
        lis[i].onclick=function(){
            this.classList.add("active");

            let rel=document.getElementsByClassName(this.getAttribute("rel"))[0];
            rel.classList.remove("hide");

            for(var j=0;j<lis.length;j++){
                if (lis[j]!=this){
                    lis[j].classList.remove("active");

                    let rel2=document.getElementsByClassName(lis[j].getAttribute("rel"))[0];
                    rel2.classList.add("hide");


                }
            };
        }
    }
*/
    // jquery版本

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

        $(this).addClass("active").siblings().removeClass("active");
        $("."+$(this).attr("rel")).removeClass("hide").siblings().addClass("hide");

    })

</script>




</body>
</html>
Tab 菜单

 

 

 

 

4.6 css操作

css位置操作

        $("").offset([coordinates])
        $("").position()
        $("").scrollTop([val])
        $("").scrollLeft([val])

示例1:

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .test1{
            width: 200px;
            height: 200px;
            background-color: wheat;
        }
    </style>
</head>
<body>


<h1>this is offset</h1>
<div class="test1"></div>
<p></p>
<button>change</button>
</body>
<script src="jquery-3.1.1.js"></script>
<script>
    var $offset=$(".test1").offset();
    var lefts=$offset.left;
    var tops=$offset.top;

    $("p").text("Top:"+tops+" Left:"+lefts);
    $("button").click(function(){

        $(".test1").offset({left:200,top:400})
    })
</script>
</html>
复制代码

示例2:

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
        }
        .box1{
            width: 200px;
            height: 200px;
            background-color: rebeccapurple;
        }
        .box2{
            width: 200px;
            height: 200px;
            background-color: darkcyan;
        }
        .parent_box{
             position: relative;
        }
    </style>
</head>
<body>




<div class="box1"></div>
<div class="parent_box">
    <div class="box2"></div>
</div>
<p></p>


<script src="jquery-3.1.1.js"></script>
<script>
    var $position=$(".box2").position();
    var $left=$position.left;
    var $top=$position.top;

    $("p").text("TOP:"+$top+"LEFT"+$left)
</script>
</body>
</html>
复制代码

示例3:

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

    <style>
        body{
            margin: 0;
        }
        .returnTop{
            height: 60px;
            width: 100px;
            background-color: peru;
            position: fixed;
            right: 0;
            bottom: 0;
            color: white;
            line-height: 60px;
            text-align: center;
        }
        .div1{
            background-color: wheat;
            font-size: 5px;
            overflow: auto;
            width: 500px;
            height: 200px;
        }
        .div2{
            background-color: darkgrey;
            height: 2400px;
        }


        .hide{
            display: none;
        }
    </style>
</head>
<body>
     <div class="div1 div">
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
           <h1>hello</h1>
     </div>
     <div class="div2 div"></div>
     <div class="returnTop hide">返回顶部</div>

 <script src="jquery-3.1.1.js"></script>
    <script>
         $(window).scroll(function(){
             var current=$(window).scrollTop();
              console.log(current);
              if (current>100){

                  $(".returnTop").removeClass("hide")
              }
              else {
              $(".returnTop").addClass("hide")
          }
         });


            $(".returnTop").click(function(){
                $(window).scrollTop(0)
            });


    </script>
</body>
</html>
复制代码

尺寸操作

复制代码
        $("").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;
        }
        .box1{
            width: 200px;
            height: 200px;
            background-color: wheat;
            padding: 50px;
            border: 50px solid rebeccapurple;
            margin: 50px;
        }

    </style>
</head>
<body>




<div class="box1">
    DIVDIDVIDIV
</div>


<p></p>

<script src="jquery-3.1.1.js"></script>
<script>
    var $height=$(".box1").height();
    var $innerHeight=$(".box1").innerHeight();
    var $outerHeight=$(".box1").outerHeight();
    var $margin=$(".box1").outerHeight(true);

    $("p").text($height+"---"+$innerHeight+"-----"+$outerHeight+"-------"+$margin)
</script>
</body>
</html>
复制代码

扩展方法 (插件机制)

jQuery.extend(object)

扩展jQuery对象本身。

用来在jQuery命名空间上增加新函数。 

在jQuery命名空间上增加两个函数:

复制代码
<script>
    jQuery.extend({
      min: function(a, b) { return a < b ? a : b; },
      max: function(a, b) { return a > b ? a : b; }
});


    jQuery.min(2,3); // => 2
    jQuery.max(4,5); // => 5
</script>
复制代码

jQuery.fn.extend(object)

扩展 jQuery 元素集来提供新的方法(通常用来制作插件)

增加两个插件方法:

复制代码
<body>

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

<script src="jquery.min.js"></script>
<script>
    jQuery.fn.extend({
      check: function() {
         $(this).attr("checked",true);
      },
      uncheck: function() {
         $(this).attr("checked",false);
      }
    });


    $(":checkbox:gt(0)").check()
</script>

</body>
复制代码

从javascript语言诞生开始,大量的开发人员使用js来完成页面特效,于是有些人就把自己工作中常用的代码段进行封装成函数或者函数库(工具库)并开源给所有开发者使用。所以javascript语言中拥有非常多,优秀的工具库。

目前全世界范围内使用最广泛的javascript函数库主要有:jQuery,Vue.js。

其中jQuery是2006年发布的工具库,jQuery简单易用,可以让开发者大量节省使用javscript开发特效的代码。

jquery 简称jQ,写jq代码,本质上就是写js代码。如果以后jQuery代码无法完成的事情,还是会使用js。

jquery的标语 Write Less, Do More(写得少,做得多)有了它,可以用更少的js代码做更多事情。

官方网站: http://jquery.com/

posted @ 2019-04-22 09:31  冥想心灵  阅读(274)  评论(0编辑  收藏  举报