jQuery

一. 简介

  • jQuery是一个轻量级的、兼容多浏览器的JavaScript库。
  • jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程

  jQuery产生的对象是jQuery独有的,只能自己调用,如果一个对象是jQuery对象,那么它就可以使用jQuery里的方法:例如$(“#i1”).html()。他的意思是:获取id值为 i1的元素的html代码。其中 html()是jQuery里的方法。相当于: document.getElementById("i1").innerHTML;

  我们在声明一个jQuery对象变量的时候在变量名前面加上$:

var $variable = jQuery对像
var variable = DOM对象
$variable[0]//jQuery对象转成DOM对象

  

  获取jQuery:

  jQuery不需要安装,把下载的jQuery库放到网站的一个公共位置,想要在某个页面上使用jQuery时,只需要在相关的HTML文档中引入该库文件即可。获得jQuery相关资源的网站地址如下:

  官网: http://jquery.com/

  源码: https://github.com/jquery/jquery

  文档: http://api.jquery.com/

  中文帮助: http://www.jquery123.com/

  CDN: http://cdn.code.baidu.com/

  jQuery1.12.1在线中文版: http://hemin.cn/jq/

  下载较新版的jQuery:下载jQuery1.11.3帮助与库

  下载最新版的jQuery:下载jQuery1.12.4库

二. 寻找元素

  基本选择器

$('li:first')    //第一个元素
$('li:last')     //最后一个元素

$("tr:even")     //索引为偶数的元素,从 0 开始
$("tr:odd")      //索引为奇数的元素,从 0 开始
 
$("tr:eq(1)")    //给定索引值的元素
$("tr:gt(0)")    //大于给定索引值的元素
$("tr:lt(2)")    //小于给定索引值的元素

$(":focus")      //当前获取焦点的元素
$(":animated")   //正在执行动画效果的元素

  层级选择器

  x和y可以为任意选择器

$("x y");// x的所有后代y(子子孙孙)
$("x > y");// x的所有儿子y(儿子)
$("x + y")// 找到所有紧挨在x后面的y
$("x ~ y")// x之后所有的兄弟y

  表单选择器

$(":input")      //匹配所有 input, textarea, select 和 button 元素
$(":text")       //所有的单行文本框
$(":password")   //所有密码框
$(":radio")      //所有单选按钮
$(":checkbox")   //所有复选框
$(":submit")     //所有提交按钮
$(":reset")      //所有重置按钮
$(":button")     //所有button按钮
$(":file")       //所有文件域
 
$("input:checked")    //所有选中的元素
$("select option:selected")    //select中所有选中的option元素

  

  筛选器

  过滤:

$("p").eq(0)       //当前操作中第N个jQuery对象,类似索引
$('li').first()    //第一个元素
$('li').last()     //最后一个元素
$(this).hasClass("test")    //元素是否含有某个特定的类,返回布尔值
$('li').has('ul')  //包含特定后代的元素

  查找

$("div").children()      //div中的每个子元素,第一层
$("div").find("span")    //div中的包含的所有span元素,子子孙孙

$("p").next()          //紧邻p元素后的一个同辈元素
$("p").nextAll()         //p元素之后所有的同辈元素
$("#test").nextUntil("#test2")    //id为"#test"元素之后到id为'#test2'之间所有的同辈元素,掐头去尾

$("p").prev()            //紧邻p元素前的一个同辈元素
$("p").prevAll()         //p元素之前所有的同辈元素
$("#test").prevUntil("#test2")    //id为"#test"元素之前到id为'#test2'之间所有的同辈元素,掐头去尾

$("p").parent()          //每个p元素的父元素
$("p").parents()         //每个p元素的所有祖先元素,body,html
$("#test").parentsUntil("#test2")    //id为"#test"元素到id为'#test2'之间所有的父级元素,掐头去尾

$("div").siblings()      //所有的同辈元素,不包括自己

三. 属性操作

  基本属性操作

$("img").attr("src");           //返回文档中所有图像的src属性值
$("img").attr("src","test.jpg");    //设置所有图像的src属性
$("img").removeAttr("src");       //将文档中图像的src属性删除

$("input[type='checkbox']").prop("checked", true);    //选中复选框
$("input[type='checkbox']").prop("checked", false);
$("img").removeProp("src");       //删除img的src属性

  css类

$("p").addClass("selected");      //为p元素加上 'selected' 类
$("p").removeClass("selected");    //从p元素中删除 'selected' 类
$("p").toggleClass("selected");    //如果存在就删除,否则就添加

  HTML代码/文本/值

$('p').html();               //返回p元素的html内容
$("p").html("Hello <b>nick</b>!");  //设置p元素的html内容
$('p').text();               //返回p元素的文本内容
$("p").text("nick");           //设置p元素的文本内容
$("input").val();             //获取文本框中的值
$("input").val("nick");          //设置文本框中的内容

四. css操作

  样式

$("p").css("color");          //访问查看p元素的color属性
$("p").css("color","red");    //设置p元素的color属性为red
$("p").css({ "color": "red", "background": "yellow" });    //设置p元素的color为red,background属性为yellow(设置多个属性要用{}字典形式)

  位置

$('p').offset()     //元素在当前视口的相对偏移,Object {top: 122, left: 260}
$('p').offset().top
$('p').offset().left
$("p").position()   //元素相对父元素的偏移,对可见元素有效,Object {top: 117, left: 250}

$(window).scrollTop()    //获取滚轮滑的高度
$(window).scrollLeft()   //获取滚轮滑的宽度
$(window).scrollTop('100')    //设置滚轮滑的高度为100

  尺寸

$("p").height();    //获取p元素的高度
$("p").width();     //获取p元素的宽度

$("p:first").innerHeight()    //获取第一个匹配元素内部区域高度(包括补白、不包括边框)
$("p:first").innerWidth()     //获取第一个匹配元素内部区域宽度(包括补白、不包括边框)

$("p:first").outerHeight()    //匹配元素外部高度(默认包括补白和边框)
$("p:first").outerWidth()     //匹配元素外部宽度(默认包括补白和边框)
$("p:first").outerHeight(true)    //为true时包括边距

  

五. 文档处理

  内部插入

$("p").append("<b>nick</b>");    //每个p元素内后面追加内容
$("p").appendTo("div");        //p元素追加到div内后
$("p").prepend("<b>Hello</b>");  //每个p元素内前面追加内容
$("p").prependTo("div");        //p元素追加到div内前

  外部插入

$("p").after("<b>nick</b>");     //每个p元素同级之后插入内容
$("p").before("<b>nick</b>");    //在每个p元素同级之前插入内容
$("p").insertAfter("#test");     //所有p元素插入到id为test元素的后面
$("p").insertBefore("#test");    //所有p元素插入到id为test元素的前面

  替换

$("p").replaceWith("<b>Paragraph. </b>");    //将所有匹配的元素替换成指定的HTML或DOM元素
$("<b>Paragraph. </b>").replaceAll("p");     //用匹配的元素替换掉所有selector匹配到的元素

  删除

$("p").empty();     //删除匹配的元素集合中所有的子节点,不包括本身
$("p").remove();    //删除所有匹配的元素,包括本身
$("p").detach();    //删除所有匹配的元素(和remove()不同的是:所有绑定的事件,附加的数据会保留下来)

  复制

$("p").clone()      //克隆元素并选中克隆的副本
$("p").clone(true)   //布尔值指事件处理函数是否会被复制

六. 事件

  页面载入

  当页面载入成功之后再运行的函数事件

$(document).ready(function(){
  do something...
});

//简写
$(function($) {
  do something...
});

  页面处理

//bind 为每个匹配元素绑定事件处理函数,绑定多个用{}。
$("p").bind("click", function(){
  alert( $(this).text() );
});
$(menuF).bind({
    "mouseover":function () {
     $(menuS).parent().removeClass("hide");
     },"mouseout":function () {
     $(menuS).parent().addClass("hide");
}
});         


$("p").one( "click", fun...)    //one 绑定一个一次性的事件处理函数
$("p").unbind( "click" )        //解绑一个事件

  页面委派

// 与bind 不同的是当时间发生时才去临时绑定。
$("p").delegate("click",function(){
  do something...
});

$("p").undelegate();       //p元素删除由 delegate() 方法添加的所有事件
$("p").undelegate("click")   //从p元素删除由 delegate() 方法添加的所有的click事件

  事件

$("p").click();      //单击事件
$("p").dblclick();    //双击事件
$("input[type=text]").focus()  //元素获得焦点时,触发 focus 事件
$("input[type=text]").blur()   //元素失去焦点时,触发 blur事件
$("button").mousedown()//当按下鼠标时触发事件
$("button").mouseup()  //元素上放松鼠标按钮时触发事件
$("p").mousemove()     //当鼠标指针在指定的元素中移动时触发事件
$("p").mouseover()     //当鼠标指针位于元素上方时触发事件
$("p").mouseout()     //当鼠标指针从元素上移开时触发事件
$(window).keydown()    //当键盘或按钮被按下时触发事件
$(window).keypress()   //当键盘或按钮被按下时触发事件,每输入一个字符都触发一次
$("input").keyup()     //当按钮被松开时触发事件
$(window).scroll()     //当用户滚动时触发事件
$(window).resize()     //当调整浏览器窗口的大小时触发事件
$("input[type='text']").change()    //当元素的值发生改变时触发事件
$("input").select()    //当input 元素中的文本被选择时触发事件
$("form").submit()     //当提交表单时触发事件
$(window).unload()     //用户离开页面时

  (event object)对象

  所有的事件函数都可以传入event参数方便处理事件

$("p").click(function(event){  
 alert(event.type); //"click"  
}); 

(evnet object)属性方法:
event.pageX   //事件发生时,鼠标距离网页左上角的水平距离
event.pageY   //事件发生时,鼠标距离网页左上角的垂直距离
event.type   //事件的类型
event.which   //按下了哪一个键
event.data   //在事件对象上绑定数据,然后传入事件处理函数
event.target  //事件针对的网页元素
event.preventDefault()  //阻止事件的默认行为(比如点击链接,会自动打开新页面)
event.stopPropagation()  //停止事件向上层元素冒泡

  

七. 效果

  基本

$("p").show()        //显示隐藏的匹配元素
$("p").show("slow");    //参数表示速度,("slow","normal","fast"),也可为900毫秒
$("p").hide()        //隐藏显示的元素
$("p").toggle();      //切换 显示/隐藏

  深入浅出

$("p").fadeIn("900");        //用900毫秒时间将段落淡入
$("p").fadeOut("900");       //用900毫秒时间将段落淡出
$("p").fadeToggle("900");     //用900毫秒时间将段落淡入,淡出
$("p").fadeTo("slow", 0.6);    //用900毫秒时间将段落的透明度调整到0.6

  滑动

$("p").slideDown("900");    //用900毫秒时间将段落滑下
$("p").slideUp("900");     //用900毫秒时间将段落滑上
$("p").slideToggle("900");  //用900毫秒时间将段落滑上,滑下

  

八. 对象访问

$.trim()   //去除字符串两端的空格
$.each()   //遍历一个数组或对象,for循环
$.inArray() //返回一个值在数组中的索引位置,不存在返回-1  
$.grep()   //返回数组中符合某种标准的元素
$.extend()  //将多个对象,合并到第一个对象
$.makeArray() //将对象转化为数组
$.type()    //判断对象的类别(函数对象、日期对象、数组对象、正则对象等等
$.isArray() //判断某个参数是否为数组
$.isEmptyObject() //判断某个对象是否为空(不含有任何属性)
$.isFunction()    //判断某个参数是否为函数
$.isPlainObject() //判断某个参数是否为用"{}"或"new Object"建立的对象
$.support()       //判断浏览器是否支持某个特性

 

九. 实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .divH {
            height: 1800px;
        }
        .divT {
             50px;
            height: 50px;
            font-size: 23px;
            background-color: #2F4F4F;
            color: white;
            position: fixed;
            right: 18px;
            bottom: 18px;
        }
        .divT:hover{
            cursor: pointer;
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
    <div class="divH"></div>
    <div class="divT hide" onclick="ReturnTop();"><strong>返回顶部</strong></div>

    <script src="../../jquery-1.12.4.js"></script>
    <script>
        window.onscroll = function () {
            var current = $(window).scrollTop();
            if (current > 180){
                $(".divT").removeClass("hide");
            }else {
                $(".divT").addClass("hide");
            }
        };

        function ReturnTop() {
            $(window).scrollTop(0);
        }
    </script>
</body>
</html>
返回顶部
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
          .menu{
              height: 600px;
               30%;
              background-color: #2F4F4F;
              float: left;
          }
         .title{
             line-height: 50px;
             color: #ddd;
         }
         .title:hover{
             cursor: pointer;
             color: lightcyan;
             font-size: 18px;
         }
         .hide{
             display: none;
         }
    </style>
</head>

<body>
    <div class="outer">
        <div class="menu">
            <div class="item">
                <div class="title" onclick="Show(this);">菜单一</div>
                <div class="con">
                    <div>111</div>
                    <div>111</div>
                    <div>111</div>
                </div>
            </div>
            <div class="item">
                <div class="title" onclick="Show(this);">菜单二</div>
                <div class="con hide">
                    <div>222</div>
                    <div>222</div>
                    <div>222</div>
                </div>
            </div>
            <div class="item">
                <div class="title" onclick="Show(this);">菜单三</div>
                <div class="con hide">
                    <div>333</div>
                    <div>333</div>
                    <div>333</div>
                </div>
            </div>
        </div>
    </div>

    <script src="../../jquery-1.12.4.js"></script>
    <script>
        function Show(self) {
            $(self).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");
        }
    </script>
</body>
</html>
左侧菜单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
             60%;
        }
        .menu{
            background-color: #cccccc;
            border: 1px solid #ccc;
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
            color: white;
        }
        .menu li:hover {
            cursor: pointer;
        }
        .menu a{
            padding: 11px;
        }
        .content{
            border: 1px solid #ccc;
            height: 300px;
            font-size: 30px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: #0099dd;
            color: black;
        }
    </style>
</head>
<body>
    <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="Tab(this);">菜单一</li>
              <li xxx="c2" onclick="Tab(this);">菜单二</li>
              <li xxx="c3" onclick="Tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>
    </div>

    <script src="../../jquery-1.12.4.js"></script>
    <script>
        function Tab(self) {
            $(self).addClass("current").siblings().removeClass("current");
            var x = "#" + $(self).attr("xxx");
            $(x).removeClass("hide").siblings().addClass("hide");
        }
    </script>
</body>
</html>
菜单切换
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
             60%;
        }
        .menu{
            background-color: #cccccc;
            border: 1px solid #ccc;
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
            color: white;
        }
        .menu li:hover {
            cursor: pointer;
        }
        .menu a{
            padding: 11px;
        }
        .content{
            border: 1px solid #ccc;
            height: 300px;
            font-size: 30px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: #0099dd;
            color: black;
        }
    </style>
</head>
<body>
    <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="Tab(this);">菜单一</li>
              <li xxx="c2" onclick="Tab(this);">菜单二</li>
              <li xxx="c3" onclick="Tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>
    </div>

    <script src="../../jquery-1.12.4.js"></script>
    <script>
        function Tab(self) {
            $(self).addClass("current").siblings().removeClass("current");
            var x = "#" + $(self).attr("xxx");
            $(x).removeClass("hide").siblings().addClass("hide");
        }
    </script>
</body>
</html>
滑动
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        ul{
            list-style: none;
        }
        .out{
             730px;
            height: 454px;
            margin: 50px auto;
            position: relative;
        }
        .out .img li{
            position: absolute;
            left: 0;
            top: 0;
        }
        .out .num{
            position: absolute;
            left:0;
            bottom: 20px;
            text-align: center;
            font-size: 0;
             100%;
        }
        .out .btn{
            position: absolute;
            top:50%;
            margin-top: -30px;
             30px;
            height: 60px;
            background-color: aliceblue;
            color: black;
            text-align: center;
            line-height: 60px;
            font-size: 40px;
            display: none;
        }
        .out .num li{
             20px;
            height: 20px;
            background-color: black;
            color: #fff;
            text-align: center;
            line-height: 20px;
            border-radius: 60%;
            display: inline;
            font-size: 18px;
            margin: 0 10px;
            cursor: pointer;
        }
        .out .num li.active{
            background-color: red;
        }
        .out .left{
            left: 0;
        }
        .out .right{
            right: 0;
        }
        .out:hover .btn{
            display: block;
            color: white;
            font-weight: 900;
            background-color: black;
            opacity: 0.8;
            cursor: pointer;
        }
        .out img {
            height: 100%;
             100%;
        }
    </style>
</head>
<body>
     <div class="out">
         <ul class="img">
             <li><a href="#"><img src="images/1.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/2.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/3.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/4.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/5.jpg" alt=""></a></li>
         </ul>

         <ul class="num">
             <!--<li class="active">1</li>-->
             <!--<li>2</li>-->
             <!--<li>3</li>-->
             <!--<li>4</li>-->
             <!--<li>5</li>-->
         </ul>

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

     </div>

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

        $(function(){
            var size=$(".img li").size();
            for (var i= 1;i<=size;i++){
                var li="<li>"+i+"</li>";
                $(".num").append(li);
            }
            $(".num li").eq(0).addClass("active");


            $(".num li").mouseover(function(){
               $(this).addClass("active").siblings().removeClass("active");
               var index=$(this).index();
               i=index;
               $(".img li").eq(index).fadeIn(1000).siblings().fadeOut(1000);
            });


        i=0;
        var t=setInterval(move,1500);

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

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

        $(".out").hover(function(){
            clearInterval(t);
        },function(){
            t=setInterval(move,1500);
        });

        $(".out .right").click(function(){
            move()
        });
        $(".out .left").click(function(){
           moveL()
        })

        });
    </script>

</body>
</html>
轮播图

  

  

生前无需久睡,死后自会长眠,努力解决生活中遇到的各种问题,不畏将来,勇敢面对,加油,你是最胖的,哈哈哈
原文地址:https://www.cnblogs.com/panshao51km-cn/p/11523974.html