jQuery

jQuery

  • jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。
  • jQuery的特点
    1. 链式编程:比如.show()和.html()可以连写成.show().html()。
    2. 隐式迭代:隐式 对应的是 显式。隐式迭代的意思是:在方法的内部进行循环遍历,而不用我们自己再进行循环,简化我们的操作,方便我们调用。
    3. 在使用jQuery的API时,都是方法调用,也就是说要加小括号(),小括号里面是相应的参数,参数不同,功能不同。
  • jQuery有三个大版本:
    1. 1.x版本:最新版为 v1.11.3
    2. 2.x版本:最新版为 v2.1.4(不再支持IE6、7、8)
    3. 3.x版本
  • jQuery操作DOM:节点操作(增删改查,克隆),文本操作,属性操作(类操作,样式操作,值操作),事件绑定
  • 官网:http://jquery.com/
  • 官网API文档:http://api.jquery.com/
  • 汉化API文档:http://www.css88.com/jqapi-1.9/
  • jquery 在线手册 :http://hemin.cn/jq/
  • 其他文档1:点击     其他文档2:点击>
  • jqueryUI 官网 :https://jqueryui.com/
  • jqueryUI 中文网 :http://www.jqueryui.org.cn/
  • 官网demo:https://www.oschina.net/project/tag/273/jquery
<script>
//原生 js 的入口函数:
//页面上所有内容加载完毕,才执行。不仅要等文本加载完毕,而且要等图片也要加载完毕,才执行函数。
window.onload = function () {
   alert(1);
};

//jQuery的入口函数,有以下几种写法:

//写法1:文档加载完毕,图片不加载的时候,就可以执行这个函数。
$(document).ready(function () {
           alert(1);
       });

//写法2:文档加载完毕,图片不加载的时候,就可以执行这个函数。(写法一的简洁版)
$(function () {
           alert(1);
       });

//写法3:文档加载完毕,图片也加载完毕的时候,在执行这个函数。
$(window).ready(function () {
           alert(1);
       });

/*
jQuery入口函数与js入口函数的区别:

区别一:书写个数不同:
    Js 的入口函数只能出现一次,出现多次会存在事件覆盖的问题。
    jQuery 的入口函数,可以出现任意多次,并不存在事件覆盖问题。

区别二:执行时机不同:
    Js的入口函数是在所有的文件资源加载完成后,才执行。这些文件资源包括:页面文档、外部的js文件、外部的css文件、图片等。
    jQuery的入口函数,是在文档加载完成后,就执行。文档加载完成指的是:DOM树加载完成后,就可以操作DOM了,不用等到所有的外部资源都加载完成。


onload是所有DOM元素创建、图片加载完毕后才触发的。
ready则是DOM元素创建完毕后触发的,不等图片加载完毕。图片还么有渲染,就可以进行事件的执行。

文档加载的顺序:从上往下,边解析边执行。
*/
</script>
入口函数
<!--需求一:有html标签关系如下,请找到所有的含有a标签的li标签-->

<ul>
    <li class="city">北京</li>
    <li class="city"><a href="">上海</a></li>
    <li class="city">天津</li>
</ul>


<script>
var objs = document.getElementsByClassName('city');
for(var i=0;i< objs.length;i++){
    arry_a = objs[i].getElementsByTagName('a');
    if(arry_a.length>0){
        console.log(objs[i]
        )
    }
}
</script>

<script>
$('li').has('a');
</script>

<!--需求二:将上面的li标签实现隔行换色效果-->
<script>
 var objs = document.getElementsByClassName('city');
    for(var i=0;i< objs.length;i++){
        if(i%2==0){
            objs[i].style.backgroundColor = 'lightblue'
        }else{
            objs[i].style.backgroundColor = 'lightyellow'
        }
    }
</script>

<script>
$('li:odd').css('background-color','lightblue');
$('li:even').css('background-color','lightyellow');
</script>


<!--需求三:点击按钮,显示页面中的三个div,并给div添加文本内容-->

<style type="text/css">
div{
     100px;
    height: 100px;
    background-color: green;
    margin-top: 20px;
    display: none;
}
</style>

<button>操作</button>
<div></div>
<div></div>
<div></div>

<script>
var oBtn = document.getElementsByTagName('button')[0];
var divArr = document.getElementsByTagName('div');
oBtn.onclick = function () {
    for (var i = 0; i < divArr.length; i++) {
        divArr[i].style.display = "block";
        divArr[i].innerHTML = "内容";
    }
}
</script>


<script>
var oBtn = $('button'); //根据标签名获取元素
var oDiv = $('div'); //根据标签名获取元素
oBtn.click(function(){
    oDiv.show(2000).html('内容');//显示盒子,设置内容
})
</script>
js和jQuery实现相同功能

一、js中的DOM对象和jQuery对象比较

  • jQuery占用了两个变量:$ 和 jQuery console.log($);console.log(jQuery);打印的值一样,所以$代表的就是jQuery。
  • jQuery 就是把 DOM 对象重新包装了一下,让其具有了 jQuery 方法。
  • jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错
  • 约定:如果获取的是 jQuery 对象, 那么要在变量前面加上$
  • jQuery对象 转为 DOM 对象:jquery对象[index](推荐) 或者 jquery对象.get(index)比如:$("#msg")[0].innerHTML
  • DOM 对象 转为 jQuery对象:$(js对象);
<div>00</div>
<div id="app">11</div>
<div class="box">22</div>
<div class="box">33</div>
<div>44</div>

<script>
//通过原生 js 获取这些元素节点的方式是:
var myBox = document.getElementById("app");           //通过 id 获取单个元素
var boxArr = document.getElementsByClassName("box");  //通过 class 获取的是伪数组
var divArr = document.getElementsByTagName("div");    //通过标签获取的是伪数组
</script>


<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
//通过 jQuery 获取这些元素节点的方式是:(获取的都是数组)
//获取的是数组,里面包含着原生 JS 中的DOM对象。
console.log($('#app'));
console.log($('.box'));
console.log($('div'));
</script>

<script>
// DOM 对象 转为 jQuery对象:
var myBox = document.getElementById("app");
console.log(myBox);
$(myBox).css("color","#f00");

//jQuery对象 转为 DOM 对象:
$('div')[1].style.backgroundColor = 'yellow';
$('div').get(3).style.backgroundColor = 'green';
</script>
View Code

二、查找元素(选择器和筛选器)

1、基本选择器
    $("*")//通用选择器
    $("#id")//id选择器
    $(".class")//class选择器
    $("element")//标签选择器
    $(".class,p,div")//并集选择器
    $("div.c1")// 交集选择器 找到有含有c1类的div标签
2、层级选择器
    $(".outer div")//后代(子子孙孙)
    $(".outer>div")//子代(所有儿子)
    $(".outer+div")//找到所有紧挨在.outer后面的div
    $(".outer~div")//.outer之后所有的兄弟div
3、属性选择器
    $('[id="div1"]')
    $("[name!='newsletter']")
    $("[name^='news']")//找所有name属性以news开头的标签
    $("input[name*='man']")//找所有name属性中含有news的input标签
    $("input[id][name$='man']")//且的关系(找所有含id且属性name以man结尾的input标签)
4、表单选择器
    $("[type='text']") = $("input:text") = $(":text")   //注意只适用于input标签
5、表单对象属性
    $("input:enabled") $("input:disabled") $("input:checked") $("select option:selected")=$("option:selected")


1、基本筛选器
    $("li:first")
    $("li:last")
    $("li:even")//索引为偶数的
    $("li:odd")//索引为奇数的
    $("li:eq(2)")//等于
    $("li:gt(1)")//大于索引1的li元素
    $("li:lt(1)")
    :not(元素选择器)// 移除所有满足not条件的标签
    :has(元素选择器)// 根据含有某个后代筛选
2、过滤筛选器方法
    $("div").first() // 获取匹配的第一个元素
    $("div").last() // 获取匹配的最后一个元素
    $("div").eq(n) // 索引值等于指定值的元素,n是索引
    $("div").not() // 从匹配元素的集合中删除与指定表达式匹配的元素
    $("div").find("p") //后代选择器,在所有div标签中找后代的p标签
    $("div").filter(".c1")  // 交集选择器,从结果集中过滤出有c1样式类的
    $("p").filter(".selected, :first") //或的关系
    $("div").has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。
    $("ul li").hasClass("test")
3、查找筛选器方法
     查找子标签(找儿子):         $("div").children(".test")
                                $("div").find("p") //后代选择器,在所有div标签中找后代的p标签

     向下查找兄弟标签(找弟弟):    $(".test").next()
                                $(".test").nextAll()
                                $("#id").nextUntil("#i2") #直到找到id为i2的标签就结束查找,不包含它

     向上查找兄弟标签(找哥哥):    $("div").prev()
                                $("div").prevAll()
                                $("#id").prevUntil("#i2")

     查找所有兄弟标签(找兄弟):    $("div").siblings() // 兄弟们,不包含自己,.siblings('#id'),可以在添加选择器进行进一步筛选

     查找父标签(找祖辈):         $(".test").parent()
                                $(".test").parents()// 查找当前元素的所有的父辈元素(爷爷辈、祖先辈都找到)
                                $("#id").parentsUntil('body')
                                // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止,这里直到body标签,不包含body标签,基本选择器都可以放到这里面使用。
4、返回(选取所有的p元素,查找并选取span子元素,然后再回过来选取p元素)
    $("p").find("span").end()

5.表单筛选器
    type筛选器
    :text
    :password
    :file
    :radio
    :checkbox
    :submit
    :reset
    :button

    其他属性筛选器
    :enabled
    :disabled
    :checked
    :selected
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        div{
            float: left;
        }
    </style>
</head>
<body>
    <div></div>
    <div id="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div></div>
    <script type="text/javascript" src="jquery3.4.1.js"></script>
    <script type="text/javascript">
        //入口函数
        $(function(){
            //三种方式获取jquery对象
            var jqBox1 = $("#box");
                   var jqBox2 = $(".box");
            var jqBox3 = $('div');
            //操作标签选择器
            jqBox3.css('width', '100');
            jqBox3.css('height', 100);
            jqBox3.css('background-color', 'red');
            jqBox3.css('margin-top', 10);
            //操作类选择器(隐式迭代,不用一个一个设置)
                    jqBox2.css("background", "green");
                    jqBox2.text('哈哈哈')

                    //操作id选择器
                    jqBox1.css("background", "yellow");

        })
    </script>

</body>
</html>
基本选择器
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="jquery-3.3.1.js"></script>
    <script>
        $(function () {
            //获取ul中的li设置为粉色
            //后代:儿孙重孙曾孙玄孙....
            var jqLi = $("ul li");
            jqLi.css("margin", 5);
            jqLi.css("background", "pink");

            //子代:亲儿子
            var jqOtherLi = $("ul>li");
            jqOtherLi.css("background", "red");
        });
    </script>
</head>
<body>
<ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <ol>
        <li>aaa</li>
        <li>bbb</li>
        <li>ccc</li>
    </ol>
</ul>
</body>
</html>
层级选择器
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
         <div id="box">
            <h2 class="title">属性元素器</h2>
            <!--<p class="p1">我是一个段落</p>-->
            <ul>
                <li id="li1">分手应该体面</li>
                <li class="what" id="li2">分手应该体面</li>
                <li class="what">分手应该体面</li>
                <li class="heihei">分手应该体面</li>

            </ul>

            <form action="" method="post">

                <input name="username" type='text' value="1" checked="checked" />
                <input name="username1111" type='text' value="1" />
                <input name="username2222" type='text' value="1" />
                <input name="username3333" type='text' value="1" />
                <button class="btn-default">按钮1</button>
                <button class="btn-info">按钮1</button>
                <button class="btn-success">按钮1</button>
                <button class="btn-danger">按钮1</button>


            </form>
        </div>
    </body>
    <script src="jquery-3.2.1.js"></script>
    <script type="text/javascript">
        
        $(function(){
            //标签名[属性名] 查找所有含有id属性的该标签名的元素
            $('li[id]').css('color','red');
            
            //匹配给定的属性是what值得元素
            $('li[class=what]').css('font-size','30px');
            //[attr!=value] 匹配所有不含有指定的属性,或者属性不等于特定值的元素
            $('li[class!=what]').css('font-size','50px');
            
            //匹配给定的属性是以某些值开始的元素
            $('input[name^=username]').css('background','gray');
            //匹配给定的属性是以某些值结尾的元素
            $('input[name$=222]').css('background','greenyellow');
            
            //匹配给定的属性是以包含某些值的元素
            $('button[class*=btn]').css('background','red')
        
            
        })
    
    </script>
</html>
属性选择器
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>基本过滤选择器</title>
    </head>
    <body>
        <ul>
            <li>哈哈哈哈,基本过滤选择器</li>
            <li>嘿嘿嘿</li>
            <li>天王盖地虎</li>
            <li>小鸡炖蘑菇</li>
            
        </ul>
    </body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        
        $(function(){
            //获取第一个 :first ,获取最后一个 :last
            
            //奇数
            $('li:odd').css('color','red');
            //偶数
            $('li:even').css('color','green');
            
            //选中索引值为1的元素 *
            $('li:eq(1)').css('font-size','30px');
            
            //大于索引值1
            $('li:gt(1)').css('font-size','50px');
            
            //小于索引值1
            $('li:lt(1)').css('font-size','12px');    
            
        })    
    </script>
</html>
基本筛选器
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
         <div id="box">
            <p class="p1">
                <span>我是第一个span标签</span>
                <span>我是第二个span标签</span>
                <span>我是第三个span标签</span>
            </p>
            <button>按钮</button>
        </div>
        <ul>
            <li class="list">2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
    </body>
    <script src="jquery-3.2.1.js"></script>
    <script type="text/javascript">
        
        //获取第n个元素 数值从0开始
        $('span').eq(1).css('color','#FF0000');
        
        //获取第一个元素 :first :last    点语法  :get方法 和set方法
        $('span').last().css('color','greenyellow');
        $('span').first().css('color','greenyellow');
        
        //查找span标签的父元素(亲的)
        $('span').parent('.p1').css({"width":'200px','height':'200px',"background":'red'});
        
        //选择所有的兄弟元素(不包括自己)
                  $('.list').siblings('li').css('color','red');

                  
                //查找所有的后代元素
                   $('div').find('button').css('background','yellow');

                
                //不写参数代表获取所有子元素。
                   $('ul').children().css("background", "green");
                   $('ul').children("li").css("margin-top", 10);
                   

        
        
    </script>
</html>
筛选器方法

三、jQuery绑定事件

1、页面载入
    $(document).ready(function(){}) =  $(function(){}) 
2、事件绑定  //语法:标签对象.事件(函数)
    $("p").click(function(){})
3、事件委派
    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。
    $("ul").on("click","li",func)  $("ul").off("click","li",func)
    $("p").on("click", function(){ alert( $(this).text());});
4、事件切换
    $(".test").hover(enter,out)
    hover事件:
        一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。
        over:鼠标移到元素上要触发的函数
        out:鼠标移出元素要触发的函数
绑定事件:
bind(type,data,fn)
描述:为每一个匹配元素的特定事件(像click)绑定一个事件处理器函数。

参数说明:
type (String) : 事件类型
data (Object) : (可选) 作为event.data属性值传递给事件对象的额外数据对象
fn ( Function) : 绑定到每个匹配元素的事件上面的处理函数

示例:当每个p标签被点击的时候,弹出其文本
$("p").bind("click", function(){
  alert( $(this).text() );
});

你可以在事件处理之前传递一些附加的数据。
function handler(event) {
//event.data 可以获取bind()方法的第二个参数的数据
  alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)


常见事件:
click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...}) //内容发生变化,input,select等
keyup(function(){...})
mouseover/mouseout
mouseenter/mouseleave
mouseover事件是如果该标签有子标签,那么移动到该标签或者移动到子标签时会连续触发,mouseenter事件不管有没有子标签都只触发一次,表示鼠标进入这个对象

通过返回false来取消默认的行为并阻止事件起泡。

$("form").bind("submit", function() { return false; })
或通过event.preventDefault() 方法阻止事件起泡

$("form").bind("submit", function(event){
  event.stopPropagation();
});



解绑事件:
unbind(type,fn);
描述:bind()的反向操作,从每一个匹配的元素中删除绑定的事件。
如果没有参数,则删除所有绑定的事件。
如果把在绑定时传递的处理函数作为第二个参数,则只有这个特定的事件处理函数会被删除。

参数说明:
type (String) : (可选) 事件类型
fn(Function) : (可选) 要从每个匹配元素的事件中反绑定的事件处理函数

示例:把所有段落的所有事件取消绑定
$("p").unbind()

将段落的click事件取消绑定
$("p").unbind( "click" )
绑定解绑bind&unbind
一次性事件:
one(type,data,fn)
描述:为每一个匹配元素的特定事件(像click)绑定一个一次性的事件处理函数。在每个对象上,这个事件处理函数只会被执行一次。其他规则与bind()函数相同

参数说明:
type (String) : 事件类型
data (Object) : (可选) 作为event.data属性值传递给事件对象的额外数据对象
fn (Function) : 绑定到每个匹配元素的事件上面的处理函数

示例:当所有段落被第一次点击的时候,显示所有其文本。
$("p").one("click", function(){
//只有第一次点击的时候才会触发,再次点击不会触发了
  alert( $(this).text() );
});
一次性事件one
<!DOCTYPE html>
<html lang="en" style="padding: 0px">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<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="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
/*
事件委托(事件代理):
原理:利用冒泡的原理,把事件加到父级上,触发执行效果。

作用:
1.性能要好
2.针对新创建的元素,直接可以拥有事件

事件源 :
  跟this作用一样(他不用看指向问题,谁操作的就是谁),event对象下的

使用情景:
  •为DOM中的很多元素绑定相同事件;
  •为DOM中尚不存在的元素绑定事件;

语法:在选定的元素上绑定一个或多个事件处理函数
on(type,selector,data,fn);

参数说明:
events( String) : 一个或多个空格分隔的事件类型
selector( String) : 一个选择器字符串,用于过滤出被选中的元素中能触发事件的后代元素
data: 当一个事件被触发时,要传递给事件处理函数的event.data。
fn:回调函数
*/


/*
    $("ul li").click(function(){
        alert(123)
    });
    $("#off").click(function(){
        $("ul li").off()
     })
*/
    $("#add_li").click(function(){
        var $ele=$("<li>");
        $ele.text(Math.round(Math.random()*10));
        $("ul").append($ele)
    });
    function test(){alert(222)}
    $("ul").on("click","li",test)
    $("#off").click(function(){
        $("ul").off("click","li",test)
     })
</script>
</body>
</html>
事件委托on&off
<!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="https://code.jquery.com/jquery-3.1.1.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>
事件切换
表单验证
表格操作

四、操作属性

1、属性
    $("").attr();  //对于HTML元素的自定义DOM属性,在处理时,使用attr方法。
    $("").removeAttr();
    $("").prop();  //对于HTML元素的固有属性,在处理时,使用prop方法。
    $("").removeProp();
    注意:
        //像checkbox,radio和select这样的元素,选中属性对应"checked"和"selected",这些也属于固有属性
        //因此需要使用prop方法去操作才能获得正确的结果。
2、HTML代码/文本/值
    $("").html([val|fn])
    $("").text([val|fn])
    $("").val([val|fn|arr])  //val 表单控件value属性
3、CSS类
    $("").addClass(class|fn)
    $("").removeClass([class|fn])
    $('div').toggleClass('box') // 如果存在(不存在)就删除(添加)一个类。
4、CSS样式
    $("#c1").css({"color":"red","fontSize":"35px"})   $("p").css("color","red")
5、位置操作
    $("").offset([coordinates]) //相对当前视口的偏移,只对可见元素有效。
    $("").position()            //相对父元素的偏移,只对可见元素有效。
    $("").scrollTop([val])      //相对滚动条的偏移,此方法对可见和隐藏元素均有效。
    $("").scrollLeft([val])
6、尺寸操作
    内容 : 宽度(width)和高度(height)
    $("").height([val|fn])
    $("").width([val|fn])       //获取宽度 返回匹配元素中第一个元素的宽,一个没有单位的数值

    内容+padding : 宽度(innerWidth)和高度(innerHeight)
    $("").innerHeight()         //获取内部区域高度(包括补白、不包括边框),此方法对可见和隐藏元素均有效。
    $("").innerWidth()

    内容+padding+border : 宽度(outerWidth)和高度(outerHeight)
    $("").outerHeight([soptions])   //获取外部高度(默认包括补白和边框),设置为true时,计算边距margin在内,此方法对可见和隐藏元素均有效。
    $("").outerHeight(true) //获取内容+padding+border+margin的高
    $("").outerWidth([options])
    $("").outerWidth(true) //获取第一个匹配元素:内容+padding+border+margin的宽
属性操作:
attr() 设置属性值、者获取属性值
//获取值:attr()设置一个属性值的时候 只是获取值
$('div').attr('id')
$('div').attr('class')

//设置值
$('div').attr('class','box') //设置一个值
$('div').attr({name:'hahaha',class:'happy'}) //设置多个值

removeAttr() 移除属性
//删除单个属性
$('#box').removeAttr('name');
$('#box').removeAttr('class');

//删除多个属性
$('#box').removeAttr('name class');

prop()
// 查看属性
$(selector).prop(property)

// 设置属性
$(selector).prop(property,value)

// 设置多个属性
$(selector).prop({property:value, property:value,...})


$('input').attr('checked')
"checked"

$('input').prop('checked')
true

$('input').prop('cheched',false)  //设置取消选中


addClass添加类名
// 为每个匹配的元素添加指定的类名。
$('div').addClass("box");//追加一个
$('div').addClass("box box2");//追加多个


removeClass移除类名
// 从所有匹配的元素中删除全部或者指定的类。
$('div').removeClass('box');//移除box类
$('div').removeClass();//移除全部的类


通过添加删除类,来实现元素的显示隐藏
var tag  = false;
$('span').click(function(){
if(tag){
    $('span').removeClass('active')
    tag=false;
}else{
    $('span').addClass('active')
    tag=true;
}
})


toggleClass类的切换
// 如果存在(不存在)就删除(添加)一个类。
$('div').toggleClass('box')

$('span').click(function(){
    //动态的切换class类名为active
    $(this).toggleClass('active')
})



val 表单控件value属性
// 获取值:用于表单控件中获取值,比如input textarea select等等
$(selector).val()

// 设置值:
$('input').val('设置了表单控件中的值')



css样式

// css(直接修改css的属性来修改样式)
$("div").css('color'); //获取

$("p").css("color", "red"); //设置
$("p").css({"color":"red","background-color":"yello"}); // 设置多个


盒子样式属性
内容 : 宽度(width)和高度(height)
// 宽度
.width() //获取宽度 返回匹配元素中第一个元素的宽,一个没有单位的数值
.width( value ) //设置宽度

//高度
.height() //获取高度 返回匹配元素中第一个元素的高,一个没有单位的数值
.height( value ) //设置高度


内容+padding : 宽度(innerWidth)和高度(innerHeight)
// 内部宽
.innerWidth() // 获取
.innerWidth(value);//设置

// 内部高
.innerHeight() // 获取
.innerHeight(value); //设置


内容+padding+border : 宽度(outerWidth)和高度(outerHeight)
// 外部宽
 .outerWidth() //获取第一个匹配元素 :内容+padding+border的宽
 .outerWidth(true) //获取第一个匹配元素:内容+padding+border+margin的宽

 .outerWidth(value) //设置多个,调整的是“内容”的宽

//外部高
 .outerHeight() //第一个匹配元素:获取内容+padding+border的高
 .outerHeight(true) //第一个匹配元素:获取内容+padding+border+margin的高

 .outerHeight( value ) //设置多个,调整的是“内容”的高



滚动条距离属性

// 水平方向
.scrollLeft()      //获取
.scrollLeft( value )//设置

// 垂直方向
.scrollTop() //获取
.scrollTop( value ) //设置
操作属性
表格全选、反选示例
addClass示例
表单示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        body{
            margin: 0;
        }
        .returnTop{
            height: 60px;
             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;
             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="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
         $(window).scroll(function(){
             var current=$(window).scrollTop();
              if (current>100){
                  $(".returnTop").removeClass("hide")
              }
              else {
              $(".returnTop").addClass("hide")
          }
         });
            $(".returnTop").click(function(){
                $(window).scrollTop(0)
            });
    </script>
</body>
</html>
返回顶部

五、操作标签

文档标签操作:
1、创建一个标签对象
    $("<p>")
2、内部插入
    父元素.append(子元素) //追加
    子元素.appendTo(父元素) //追加
    父元素.prepend(子元素) // 前置添加
    子元素.prependTo(父元素) // 前置添加
3、外部插入
    兄弟元素.after(要插入的兄弟元素) // 在匹配的元素之后插入内容
    要插入的兄弟元素.inserAfter(兄弟元素) // 在匹配的元素之后插入内容
    兄弟元素.before(要插入的兄弟元素); // 在匹配的元素之前插入内容
    要插入的兄弟元素.inserBefore(兄弟元素); // 在匹配的元素之前插入内容
4、修改/替换
    $(selector).replaceWith(content); // selector被替换:将所有匹配的元素替换成指定的string、js对象、jquery对象。
    $('<p>哈哈哈</p>')replaceAll(selector);// selector被替换:将所有的匹配的元素替换成p标签。
5、删除
    $("").empty() // 清空选中元素中的所有后代节点
    $("").remove([expr]) //删除节点后,事件也会删除(简言之,删除了整个标签)
    $(selector).detach(); // 删除节点后,事件会保留
6、复制
    $("").clone([Even[,deepEven]])

标签内文本操作:
HTML代码/文本/值
    $("").html([val|fn])
    $("").text([val|fn])
    $("").val([val|fn|arr])
标签内文本操作:
    html 标签元素中所有的内容:

    //获取值:获取选中标签元素中所有的内容
    $('#box').html();

    //设置值:设置该元素的所有内容 会替换掉 标签中原来的内容
    $('#box').html('<a href="https://www.baidu.com">百度一下</a>');

    text 标签元素的文本内容:

    //获取值:获取选中标签元素中的文本内容
    $('#box').text();

    //设置值:设置该所有的文本内容
    $('#box').text('<a href="https://www.baidu.com">百度一下</a>');
    注意:text()方法接收的值为标签的时候 不会被渲染为标签元素 只会被当做值渲染到浏览器中




文档标签操作:

    之前js中咱们学习了js的DOM操作,也就是所谓的增删改查DOM操作。通过js的DOM的操作,大家也能发现,大量的繁琐代码实现我们想要的效果。那么jQuery的文档操作的API提供了便利的方法供我们操作我们的文档。

    看一个之前我们js操作DOM的例子:

    var oUl = document.getElementsByTagName('ul')[0];
    var oLi = document.createElement('li');
    oLi.innerHTML = '内容';
    oUl.appendChild(oLi);


插入标签
    append和appendTo

    //追加某元素,在父元素中添加新的子元素。子元素可以为:stirng | element(js对象) | jquery元素
    父元素.append(子元素)

    //追加到某元素,子元素添加到父元素
    子元素.appendTo(父元素)

    //append
    var oli = document.createElement('li');
    oli.innerHTML = '哈哈哈';
    $('ul').append('<li>1233</li>');
    $('ul').append(oli);
    $('ul').append($('#app'));

    //appendTo
    $('<li>天王盖地虎</li>').appendTo($('ul')).addClass('active')

    PS:如果追加的jquery对象原本在文档树中,那么这些元素将从原位置上消失。简言之,就是移动操作。


    prepend和prependTo

    // 前置添加, 添加到父元素的第一个位置
    父元素.prepend(子元素);

    // 前置添加, 添加到父元素的第一个位置
    子元素.prependTo(父元素);

    // prepand
    $('ul').prepend('<li>我是第一个</li>')
    // prependTo
    $('<a href="#">路飞学诚</a>').prependTo('ul')


    after和insertAfter

    // 在匹配的元素之后插入内容
    兄弟元素.after(要插入的兄弟元素);
    要插入的兄弟元素.inserAfter(兄弟元素);


    $('ul').after('<h4>我是一个h3标题</h4>')
    $('<h5>我是一个h2标题</h5>').insertAfter('ul')


    before和insertBefore

    // 在匹配的元素之前插入内容
    兄弟元素.before(要插入的兄弟元素);
    要插入的兄弟元素.inserBefore(兄弟元素);

    //示例
    $('ul').before('<h3>我是一个h3标题</h3>')
    $('<h2>我是一个h2标题</h2>').insertBefore('ul')



删除标签 remove、detach和empty
    //删除节点后,事件也会删除(简言之,删除了整个标签)
    $(selector).remove();

    // 删除节点后,事件会保留
    $(selector).detach();

    // 清空选中元素中的所有后代节点
    $(selector).empty();

    // remove
    $('ul').remove();

    // detach
    var $btn = $('button').detach()
    $('ul').append($btn) //此时按钮能追加到ul中

    //empty
    $('ul').empty() //清空掉ul中的子元素,保留ul



修改标签 replaceWith和replaceAll
    // selector被替换:将所有匹配的元素替换成指定的string、js对象、jquery对象。
    $(selector).replaceWith(content);

    // selector被替换:将所有的匹配的元素替换成p标签。
    $('<p>哈哈哈</p>')replaceAll(selector);

    // replaceWith
    $('h5').replaceWith('<a href="#">hello world</a>') //将所有的h5标题替换为a标签
    $('h5').replaceWith($('#app')); //将所有h5标题标签替换成id为app的dom元素

    // replaceAll
    $('<br/><hr/><button>按钮</button>').replaceAll('h4')


克隆标签 clone
    // 克隆匹配的DOM元素
    $(选择器).clone();

    $('button').click(function() {
     // 1.clone():克隆匹配的DOM元素
     // 2.clone(true):元素以及其所有的事件处理并且选中这些克隆的副本(简言之,副本具有与真身一样的事件处理能力)
      $(this).clone(true).insertAfter(this);
    })
标签操作

六、each循环

  • $.each(obj,fn)
  • $("").each(fn)
  • each扩展
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
li=[10,20,30,40];
dic={name:"alex",sex:"male"};
list=[{name:"alex",sex:"male"},{name:"alex22",sex:"female"}];
$.each(li,function(i,x){
    console.log(i,x)
});
$.each(dic,function(i,x){
    console.log(i,x)
});
$.each(list,function(i,x){
    console.log(i,x)
});
/*
0 10
1 20
2 30
3 40
name alex
sex male
0 {name: "alex", sex: "male"}
1 {name: "alex22", sex: "female"}
*/
</script>
$.each(obj,fn)
<body>
<p>111</p>
<p>222</p>
<p>333</p>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$("p").each(function(){
    console.log($(this).html())  //$(this)代指当前循环标签。
})
/*
111
222
333
*/
</script>
$("").each(fn)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 
<p>111</p>
<p>222</p>
<p>333</p>
<p>444</p>
<p>555</p>
</body>
 
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function f(){
    for(var i=0;i<4;i++){
        if (i==2){
            return
        }
        console.log(i) // 1,2
        }
    }
    f(); 
      
    $.each($("p"),function(i,v){
        if (i==2){
                return false; 
            }
            console.log(v)   // <p>111</p> <p>222</p>
    });
      
    $.each($("p"),function(i,v){
    if (i==2){
            return true; 
        }
        console.log(v)  //<p>111</p><p>222</p><p>333</p><p>444</p><p>555</p>
    });
      
    li=[11,22,33,44];
    $.each(li,function(i,v){
        if (v==33){
                return ;  
            }
            console.log(v)  //11,22,44
    });
      
    $.each(li,function(i,v){
    if (v==33){
            return false;  
        }
        console.log(v)  //11,22
    });
    // <1>如果你想return后下面循环函数继续执行,那么就直接写return或return true
    // <2>如果你不想return后下面循环函数继续执行,那么就直接写return false
</script>
</html>
each扩展

七、动画效果

  • jQuery提供的一组网页中常见的动画效果,这些动画是标准的、有规律的效果;同时还提供给我们了自定义动画的功能。
<script>
/*
显示动画:
方式一:无参数,表示让指定的元素直接显示出来。其实这个方法的底层就是通过display: block;实现的。
$("div").show();

方式二:通过控制元素的宽高、透明度、display属性,逐渐显示,例如:3秒后显示完毕。
$('div').show(3000);

方式三:和方式二类似,也是通过控制元素的宽高、透明度、display属性,逐渐显示。
$("div").show("slow");

方式四:动画执行完后,立即执行回调函数。
//show(毫秒值,回调函数;
$("div").show(5000,function () {
    alert("动画执行完毕!");
});

参数说明:
slow 慢:600ms
normal 正常:400ms
fast 快:200ms

总结:上面的四种方式几乎一致:参数可以有两个,第一个是动画的执行时长,第二个是动画结束后执行的回调函数。


隐藏动画:
方式参照上面的show()方法的方式。如下:
$(selector).hide();
$(selector).hide(1000);
$(selector).hide("slow");
$(selector).hide(1000, function(){});
*/

//显隐
$(document).ready(function() {
    $("#hide").click(function () {
        $("p").hide(1000);
    });
    $("#show").click(function () {
        $("p").show(1000);
    });
});
    
    
/*
开关式显示隐藏动画
$('#box').toggle(3000,function(){});
显示和隐藏的来回切换采用的是toggle()方法:就是先执行show(),再执行hide()。
*/

$(document).ready(function() {
//用于切换被选元素的 hide() 与 show() 方法。
    $("#toggle").click(function () {
        $("p").toggle();
    });
});


$('#btn').click(function(){
        $('#box').toggle(3000,function(){
            $(this).text('盒子出来了');
            if ($('#btn').text()=='隐藏') {
                $('#btn').text('显示');
            }else{
                $('#btn').text('隐藏');
            }
        });
})
    
</script>
显隐
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #box{
                 200px;
                height: 200px;
                background-color: green;
                border: 1px solid red;
                display: none;
            }
        </style>
    </head>
    <body>
        <div id="box">        
        </div>
        <button id="btn">隐藏</button>    
    </body>
    <script src="jquery-3.3.1.js"></script>
    
    <script type="text/javascript">
        
        //jquery 提供了一些方法 show() hide() 控制元素显示隐藏
        var isShow = true;
        $('#btn').click(function(){
            if(isShow){
                $('#box').show('slow',function(){
                    $(this).text('盒子出来了');            
                    $('#btn').text('显示');
                    isShow = false;
                })
            }else{
                $('#box').hide(2000,function(){
                    $(this).text('');    
                    $('#btn').text('隐藏');
                    isShow = true;
                    
                })
            }
        })
    
        
    </script>
</html>
示例
<script>
/*
1、滑入动画效果:(类似于生活中的卷帘门):下拉动画,显示元素。
$(selector).slideDown(speed, 回调函数);
注意:省略参数或者传入不合法的字符串,那么则使用默认值:400毫秒(同样适用于fadeIn/slideDown/slideUp)

2、滑出动画效果: 上拉动画,隐藏元素。
$(selector).slideUp(speed, 回调函数);

3、滑入滑出切换动画效果:
$(selector).slideToggle(speed, 回调函数);
*/

$(document).ready(function(){
 $("#slideDown").click(function(){
     $("#content").slideDown(1000);
 });
  $("#slideUp").click(function(){
     $("#content").slideUp(1000);
 });
  $("#slideToggle").click(function(){
     $("#content").slideToggle(1000);
 })
});
</script>
滑动
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        div {
             300px;
            height: 300px;
            display: none;
            background-color: green;
        }
    </style>

    <script src="jquery-3.3.1.js"></script>
    <script>
        $(function () {
            //点击按钮后产生动画
            $("button:eq(0)").click(function () {

                //滑入动画: slideDown(毫秒值,回调函数[显示完毕执行什么]);
                $("div").slideDown(2000, function () {
                    alert("动画执行完毕!");
                });
            })

            //滑出动画
            $("button:eq(1)").click(function () {

                //滑出动画:slideUp(毫秒值,回调函数[显示完毕后执行什么]);
                $("div").slideUp(2000, function () {
                    alert("动画执行完毕!");
                });
            })

            $("button:eq(2)").click(function () {
                //滑入滑出切换(同样有四种用法)
                $("div").slideToggle(1000);
            })

        })
    </script>
</head>
<body>
<button>滑入</button>
<button>滑出</button>
<button>切换</button>
<div></div>

</body>
</html>
示例
<script>
/*
1、淡入动画效果:让元素以淡淡的进入视线的方式展示出来。
$(selector).fadeIn(speed, callback);

2、淡出动画效果:让元素以渐渐消失的方式隐藏起来
$(selector).fadeOut(1000);

3、淡入淡出切换动画效果:通过改变透明度,切换匹配元素的显示或隐藏状态。
$(selector).fadeToggle('fast', callback);
参数的含义同show()方法。
*/

//淡入淡出
$(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>
淡入淡出
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        div {
             300px;
            height: 300px;
            display: none;
            /*透明度*/
            opacity: 0.5;
            background-color: red;
        }
    </style>

    <script src="jquery-3.3.1.js"></script>
    <script>
        $(function () {
            //点击按钮后产生动画
            $("button:eq(0)").click(function () {

//                //淡入动画用法1:   fadeIn();   不加参数
                $("div").fadeIn();

//                //淡入动画用法2:   fadeIn(2000);   毫秒值
//                $("div").fadeIn(2000);
//                //通过控制  透明度和display

                //淡入动画用法3:   fadeIn(字符串);   slow慢:600ms   normal正常:400ms   fast快:200ms
//                $("div").fadeIn("slow");
//                $("div").fadeIn("fast");
//                $("div").fadeIn("normal");

                //淡入动画用法4:   fadeIn(毫秒值,回调函数[显示完毕执行什么]);
//                $("div").fadeIn(5000,function () {
//                    alert("动画执行完毕!");
//                });
            })

            //滑出动画
            $("button:eq(1)").click(function () {
//                //滑出动画用法1:   fadeOut();   不加参数
               $("div").fadeOut();

//                //滑出动画用法2:   fadeOut(2000);   毫秒值
//                $("div").fadeOut(2000);  //通过这个方法实现的:display: none;
//                //通过控制  透明度和display

                //滑出动画用法3:   fadeOut(字符串);   slow慢:600ms   normal正常:400ms   fast快:200ms
//                $("div").fadeOut("slow");
//                $("div").fadeOut("fast");
//                $("div").fadeOut("normal");

                //滑出动画用法1:   fadeOut(毫秒值,回调函数[显示完毕执行什么]);
//                $("div").fadeOut(2000,function () {
//                    alert("动画执行完毕!");
//                });
            })

            $("button:eq(2)").click(function () {
                //滑入滑出切换
                //同样有四种用法
                $("div").fadeToggle(1000);
            })

            $("button:eq(3)").click(function () {
                //改透明度
                //同样有四种用法
                $("div").fadeTo(1000, 0.5, function () {
                    alert(1);
                });
            })
        })
    </script>
</head>
<body>
<button>淡入</button>
<button>淡出</button>
<button>切换</button>
<button>改透明度为0.5</button>
<div></div>

</body>
</html>
示例
<script>
/*
自定义动画

语法:
$(selector).animate({params}, speed, callback);

作用:执行一组CSS属性的自定义动画。

第一个参数表示:要执行动画的CSS属性(必选)

第二个参数表示:执行动画时长(可选)

第三个参数表示:动画执行完后,立即执行的回调函数(可选)


停止动画
$(selector).stop(true, false);

参数说明:
第一个参数:
true:后续动画不执行。
false:后续动画会执行。

第二个参数:
true:立即执行完成当前动画。
false:立即停止当前动画。

PS:参数如果都不写,默认两个都是false。实际工作中,直接写stop()用的多。
*/

//关键的地方在于,用了stop函数,再执行动画前,先停掉之前的动画。

</script>
自定义动画
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        div {
            position: absolute;
            left: 20px;
            top: 30px;
             100px;
            height: 100px;
            background-color: green;
        }
    </style>
    <script src="jquery-3.3.1.js"></script>
    <script>
        jQuery(function () {
            $("button").click(function () {
                var json = {"width": 500, "height": 500, "left": 300, "top": 300, "border-radius": 100};
                var json2 = {
                    "width": 100,
                    "height": 100,
                    "left": 100,
                    "top": 100,
                    "border-radius": 100,
                    "background-color": "red"
                };

                //自定义动画
                $("div").animate(json, 1000, function () {
                    $("div").animate(json2, 1000, function () {
                        alert("动画执行完毕!");
                    });
                });

            })
        })
    </script>
</head>
<body>
<button>自定义动画</button>
<div></div>
</body>
</html>
示例
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        ul {
            list-style: none;
        }

        .wrap {
             330px;
            height: 30px;
            margin: 100px auto 0;
            padding-left: 10px;
            background-color: pink;
        }

        .wrap li {
            background-color: green;
        }

        .wrap > ul > li {
            float: left;
            margin-right: 10px;
            position: relative;
        }

        .wrap a {
            display: block;
            height: 30px;
             100px;
            text-decoration: none;
            color: #000;
            line-height: 30px;
            text-align: center;
        }

        .wrap li ul {
            position: absolute;
            top: 30px;
            display: none;
        }
    </style>
    <script src="jquery-3.3.1.js"></script>
    <script>
        //入口函数
        $(document).ready(function () {
            //需求:鼠标放入一级li中,让他里面的ul显示。移开隐藏。
            var jqli = $(".wrap>ul>li");

            //绑定事件
            jqli.mouseenter(function () {
                $(this).children("ul").stop().slideDown(1000);
            });

            //绑定事件(移开隐藏)
            jqli.mouseleave(function () {
                $(this).children("ul").stop().slideUp(1000);
            });
        });
    </script>

</head>
<body>
<div class="wrap">
    <ul>
        <li>
            <a href="javascript:void(0);">一级菜单1</a>
            <ul>
                <li><a href="javascript:void(0);">二级菜单2</a></li>
                <li><a href="javascript:void(0);">二级菜单3</a></li>
                <li><a href="javascript:void(0);">二级菜单4</a></li>
            </ul>
        </li>
        <li>
            <a href="javascript:void(0);">二级菜单1</a>
            <ul>
                <li><a href="javascript:void(0);">二级菜单2</a></li>
                <li><a href="javascript:void(0);">二级菜单3</a></li>
                <li><a href="javascript:void(0);">二级菜单4</a></li>
            </ul>
        </li>
        <li>
            <a href="javascript:void(0);">三级菜单1</a>
            <ul>
                <li><a href="javascript:void(0);">三级菜单2</a></li>
                <li><a href="javascript:void(0);">三级菜单3</a></li>
                <li><a href="javascript:void(0);">三级菜单4</a></li>
            </ul>
        </li>
    </ul>
</div>
</body>
</html>
停止动画

八、回调函数

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
  <button>fadeToggle</button>
  <p>helloworld helloworld helloworld</p>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
   $("button").click(function(){
       $("p").fadeToggle(1000,function(){
           console.log($(this).html())
       })
   })
</script>
</body>
</html>
View Code

九、扩展方法 (插件机制)

1、jQuery.extend(object)

  • 扩展jQuery对象本身。
  • 用来在jQuery命名空间上增加新函数。

2、jQuery.fn.extend(object)

  • 扩展jQuery元素集来提供新的方法(通常用来制作插件)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    //扩展jQuery对象本身
    jQuery.extend({
      min: function(a, b) { return a < b ? a : b; },
      max: function(a, b) { return a > b ? a : b; }
});
    console.log(jQuery.min(2,3)); // => 2
    console.log(jQuery.max(4,5)); // => 5
     
    //元素
    jQuery.fn.extend({
      check: function() {
         $(this).attr("checked",true);
      },
      uncheck: function() {
         $(this).attr("checked",false);
      }
    });
 
    $(":checkbox:gt(0)").check()
</script>
</html>
View Code

十、实例练习

左侧菜单 

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

    <style>
          .menu{
              height: 500px;
               20%;
              background-color: gainsboro;
              text-align: center;
              float: left;
          }
          .content{
              height: 500px;
               80%;
              background-color: darkgray;
              float: left;
          }
         .title{
             line-height: 50px;
             background-color: wheat;
             color: rebeccapurple;}


         .hide{
             display: none;
         }


    </style>
</head>
<body>

<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜单二</div>
            <div class="con hide">
                <div>222</div>
                <div>222</div>
                <div>222</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜单三</div>
            <div class="con hide">
                <div>333</div>
                <div>333</div>
                <div>333</div>
            </div>
        </div>

    </div>
    <div class="content"></div>

</div>
<script src="jquery.min.js"></script>
<script>
           $(".item .title").mouseover(function () {
                $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");

//                $(this).next().removeClass("hide");
//                $(this).parent().siblings().children(".con").addClass("hide");
           })
</script>


</body>
</html>
View Code

Tab切换

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

    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .tab_outer{
            margin: 20px auto;
             60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
            text-align: center;
        }
        .menu li{
            display: inline-block;
            margin-left: 14px;
            padding:5px 20px;

        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;

        }
        .hide{
            display: none;
        }

        .current{
            background-color: #2868c8;
            color: white;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li relation="c1" class="current">菜单一</li>
              <li relation="c2" >菜单二</li>
              <li relation="c3">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>

      </div>
</body>


<script src="jquery.min.js"></script>
    <script>
          $(".menu li").click(function(){

               var index=$(this).attr("relation");
               $("#"+index).removeClass("hide").siblings().addClass("hide");
               $(this).addClass("current").siblings().removeClass("current");

          });


    </script>
</html>
View Code

table正反选

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

</head>
<body>

     <button>全选</button>
     <button>取消</button>
     <button>反选</button>
     <hr>
     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
             <td>111</td>
             <td>111</td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
             <td>222</td>
             <td>222</td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
             <td>333</td>
             <td>333</td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
             <td>444</td>
             <td>444</td>
             <td>444</td>
         </tr>
     </table>




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

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

               if($(this).text()=="全选"){    // $(this)代指当前点击标签

                   $("table :checkbox").prop("checked",true)
               }
                else if($(this).text()=="取消"){
                   $("table :checkbox").prop("checked",false)
               }
                else {
                   $("table :checkbox").each(function(){

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

                 });
               }



            });

    </script>
</body>
</html>
View Code

模态对话框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
        }
        .back{
            background-color: wheat;
            height: 2000px;
        }

        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left:0;
            right: 0;
            background-color: darkgray;
            opacity: 0.4;
        }

        .hide{
            display: none;
        }

        .models{
            position: fixed;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
            height: 200px;
             200px;
            background-color: white;

        }
    </style>
</head>
<body>
<div class="back">
    <input id="ID1" type="button" value="click" onclick="action1(this)">
</div>

<div class="shade hide"></div>
<div class="models hide">
    <input id="ID2" type="button" value="cancel" onclick="action2(this)">
</div>


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

    function action1(self){
        $(self).parent().siblings().removeClass("hide");

    }
    function action2(self){
        //$(self).parent().parent().children(".models,.shade").addClass("hide")

        $(self).parent().addClass("hide").prev().addClass("hide")

    }
</script>
</body>
</html>
View Code

复制样式条

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

</head>
<body>
            <div class="outer">
                <div class="item">
                        <input type="button" value="+">
                        <input type="text">
                </div>
            </div>


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

            function add(self){
                // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
                 var $clone_obj=$(self).parent().clone();
                 $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
                 $(self).parent().parent().append($clone_obj);
            }
           function removed(self){

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

           }


/*
        $("[value='+']").click(function(){

             var $clone_obj=$(this).parent().clone();
                 $clone_obj.children(":button").val("-").attr("class","mark");
                 $(this).parent().parent().append($clone_obj);

        });



        $(".outer").on("click",".item .mark",function(){

            console.log($(this));  // $(this):  .item .mark标签
            $(this).parent().remove()

        })

*/


    </script>
</body>
</html>
View Code

注册验证

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



<form class="Form" id="form">

    <p><input class="v1" type="text" name="username" mark="用户名"></p>
    <p><input class="v1" type="text" name="email" mark="邮箱"></p>
    <p><input type="submit" value="submit"></p>

</form>

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


    $("#form :submit").click(function(){
          flag=true;

          $("#form .v1").each(function(){

          $(this).next("span").remove();// 防止对此点击按钮产生多个span标签

          var value=$(this).val();

          if (value.trim().length==0){
                 var mark=$(this).attr("mark");
                 var ele=document.createElement("span");
                 ele.innerHTML=mark+"不能为空!";
                 $(this).after(ele);
                 $(ele).prop("class","error");// DOM对象转换为jquery对象
                 flag=false;
                 return false ; //-------->引出$.each的return false注意点
            }

        });

        return flag
    });




</script>
</body>
</html>
View Code

拖动面板

<!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.min.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).on('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).off('mousemove');
        });
    })
</script>
</body>
</html>
View Code

轮播图

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


    <style>

            .outer{
                 790px;
                height: 340px;
                margin: 80px auto;
                position: relative;
            }

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

           .num{
               position: absolute;
               bottom: 18px;
               left: 270px;
               list-style: none;


           }

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

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

               text-align: center;
               line-height: 60px;
               font-size: 30px;
               opacity: 0.7;
               margin-top: -30px;

               display: none;

           }

           .left{
               left: 0;
           }

           .right{
               right: 0;
           }

          .outer:hover .btn{
              display: block;
          }

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

</head>
<body>


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

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

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

      </div>
<script src="jquery-3.1.1.js"></script>
<script>
    var i=0;
//  通过jquery自动创建按钮标签

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

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

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


// 手动轮播

    $(".num li").mouseover(function () {
        i=$(this).index();
        $(this).addClass("active").siblings().removeClass("active");

        $(".img li").eq(i).stop().fadeIn(200).siblings().stop().fadeOut(200)

    });


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

    function GO_R() {

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

    }


    function GO_L() {
        if(i==0){
            i=img_num
        }
         i--;
         $(".num li").eq(i).addClass("active").siblings().removeClass("active");
         $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);  // fadeIn,fadeOut单独另开启的线程


    }
    $(".outer").hover(function () {
        clearInterval(c)
    },function () {
        c=setInterval(GO_R,1500)
    });



// button 加定播 
    $(".right").click(GO_R);
    $(".left").click(GO_L)



</script>
</body>
</html>
View Code

表格编辑操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="jquery-2.1.4.min.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>

    <style>

        .container .row td{
            padding: 10px;
        }

        #box{

          padding-top:50px;
        }

       .add{
           margin:20px 0;
       }

    </style>
</head>
<body>




<div class="container">
    <div class="row">

        <div class="col-md-7 col-lg-offset-3" id="box" >
            <div>
                <button type="button" class="btn btn-success add" data-toggle="modal" data-target="#myModal">
                添加员工信息
                </button>
            </div>

            <table class="table table-striped">
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>部门</th>
                    <th>薪水</th>
                    <th>操作</th>
                </tr>

                <tr>
                    <td>张三</td>
                    <td>23</td>
                    <td>销售部</td>
                    <td>3000</td>
                    <td>
                        <button class="btn btn-danger btn-sm del">删除</button>
                        <button class="btn btn-info btn-sm edit">编辑</button>
                        <button class="btn btn-primary btn-sm">查看</button>
                    </td>
                </tr>

                 <tr class="handle">
                    <td>李四</td>
                    <td>32</td>
                    <td>保安部</td>
                    <td>5000</td>
                    <td>
                        <button class="btn btn-danger btn-sm del">删除</button>
                        <button class="btn btn-info btn-sm edit">编辑</button>
                        <button class="btn btn-primary btn-sm">查看</button>
                    </td>
                </tr>
            </table>
        </div>

    </div>

</div>


<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">

          <div class="row">

              <div class="col-md-5 col-lg-offset-3">
                        <form class="add_form edit_form">
                              <div class="form-group">
                                <label for="username">姓名</label>
                                <input type="text" class="form-control" id="username" placeholder="username">
                              </div>
                              <div class="form-group">
                                <label for="age">年龄</label>
                                <input type="text" class="form-control" id="age" placeholder="age">
                              </div>
                              <div class="form-group">
                                <label for="dep">部门</label>
                                <input type="text" id="dep" placeholder="dep" class="form-control">

                              </div>

                               <div class="form-group">
                                <label for="salary">薪水</label>
                                <input type="text" class="form-control" id="salary" placeholder="salary">
                              </div>
                          </form>
              </div>
          </div>


      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary add_save">Save changes</button>
        <button type="button" class="btn btn-primary edit_save" style="display: none">Save changes</button>

      </div>
    </div>
  </div>
</div>


<script>
         // 提炼出一个创建tr的函数
         function createTr(){
             var $tr=$("<tr>");

             $(".add_form :text").each(function(){

                 $tr.append($("<td>").html($(this).val()))
             });


             $handle=$(".handle td:last").clone();
             $tr.append($handle);

             return $tr
         }

         // 添加按钮

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



             $("#myModal").modal("hide");

             var $tr=createTr();


             $(".table tbody").append($tr)

         });

         // 删除按钮
         $("table").on("click",".del",function(){
            $(this).parent().parent().remove()
         });

         //编辑按钮

         $("table").on("click",".edit",function(){
             var $edit_obj=$(this).parent().parent();
             var arr=[];
             $(this).parent().siblings().each(function(){
                 arr.push($(this).text())

             });

             $(".edit_form :text").each(function(i){
                  $(this).val(arr[i])
             });

             $("#myModal").modal("show");


              $(".edit_save").show().prev().hide();
              $(".edit_save").click(function(){
                  $("#myModal").modal("hide");

                  // 创建tr标签
                 var $tr=createTr();
                 $edit_obj.replaceWith($tr);
                 $(".edit_save").hide().prev().show();
             });

          })


</script>




</body>
</html>
View Code

注册实例

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

    <style>
        .error{
            color:red
        }
    </style>
</head>
<body>


<form class="Form">

    <p><input class="v1" type="text" name="username" mark="用户名"></p>
    <p><input class="v1" type="text" name="email" mark="邮箱"></p>
    <p><input type="submit" value="submit"></p>

</form>

<script src="jquery-2.1.4.min.js"></script>

<script>
    $(".Form :submit").click(function(){

        flag=true;

        $("Form .v1").each(function(){

            var value=$(this).val();
            if (value.trim().length==0){
                 var mark=$(this).attr("mark");
                 var $span=$("<span>");
                 $span.html(mark+"不能为空!");
                 $span.prop("class","error");
                 $(this).after($span);

                 setTimeout(function(){
                      $span.remove();
                 },800);

                 flag=false;
                 return flag;
            }

        });

        return flag



    });


</script>



</body>
</html>
View Code
实例:加载
实例:Tab菜单-html
实例:返回顶部
实例:多选、反选和取消
实例:滚动菜单
实例:滚动菜单
实例:移动面板
实例:Ajax跨域
原文地址:https://www.cnblogs.com/bubu99/p/10463843.html