前端之jQuery

一  什么是jQuery

  1. jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team
  2. jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE
  3. 它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器
  4. jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。
  5. jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。

学习文档可参考:http://jquery.cuishifeng.cn/

二 使用jQuery

jQuery是一个纯JavaScript客户端库,全部代码被封装在一个文件中。jQuery有以下两种形式的发布版:

  • 压缩发布版:compressed,用于正式发布,以*.min.js命名,比如:jquery-1.11.2.min.js
  • 正常发布版:uncompressed,用于阅读和调试,以*.js命名,比如:jquery-1.11.2.js

每个版本的两种形式在功能上完全相同,只是压缩发布的文件更小。开发者通常在项目开放中使用正常发布版,在项目实际运行中为了使网页更快的被加载而使用压缩发布版。

我们可以直接在HTML源文件中引用Internet上的jQuery库连接,比如:

<script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>

使用技巧:使用Internet上的jQuery库,而不是将其下载到本地再引用有好处,即Internet上的这些jQuery库都做了CDN加速,通常在客户端下载这些文件的速度比下载开发者站点的速度要快。

在JavaScript中调用jQuery以如下基础语法形式实现:

$(selector).action()

其中$指明引用jQuery库;selector为选择器,用来筛选页面标记元素;action即行为,是对筛选的元素进行的操作。

一个示例分析:

$("#d1").html()
// 获取ID为d1的元素内的html代码。其中html()是jQuery里的方法
// $()括号中元素必须加""双引号
// 这段代码等同于用DOM实现代码:document.getElementById("d1").innerHTML
// 虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法,乱使用会报错

补充1--什么是jQuery对象

jQuery对象就是通过jQuery包装DOM对象后产生的对象。jQuery对象是 jQuery 独有的如果一个对象是 jQuery对象,那么它就可以使用 jQuery 里的方法。

补充2--约定:如果获取的是jQuery对象, 我们在变量前面加上$

var $variable = jQuery 对象
var variable = DOM 对象

补充3--jQuery对象与DOM对象相互转换

// $variable[0]:jQuery对象转为DOM对象
$("#d1").html() = $("#d1")[0].innerHTML
// $(variable):DOM对象转为jQuery对象
$(document.getElementById('d1') = $("#d1")

三 选择器

jQuery中的选择器的概念与CSS中的选择器类似,但是除了按标记名、id等进行选择,jQuery的选择器的功能更丰富,比如:根据标记的特定属性进行选择、根据标记相对于父标记的位置进行选择、根据元素内容进行选择等。

3.1 基本选择器

//id选择器:$("#id值")
$("#d1")            //选取id为“d1”的元素

//类选择器:$(".class值")        
$(".c1")            //选取class名为c1的元素

//元素选择器:$("标签名")       
$("p")              //选取标签为p的元素

//组合选择器:$("xx,xxx")       
$("#d1,.c1")        //选取id为“d1”的或class名为c1的元素

//所有标签
$("*")              //选取所有元素

3.2 层级选择器

$(".outer div")       //选取class为outer的后代<div>元素
$(".outer>div")       //选取class为outer的子代<div>元素
$(".outer+div")       //选取class为outer的毗邻<div>元素
$(".outer~div")       //选取class为outer的兄弟<div>元素

3.3 过滤选择器

3.3.1 基本过滤选择器

//$(" :first"):选取第一个元素
$("li:first")                   //选取第一个<li>元素
$("ul li:first")                //选取第一个<ul>元素的第一个<li>元素
$("ul li:first-child")          //选取每一个<ul>元素的第一个<li>元素

//$(" :last"):选取最后一个元素
$("li:last")          //选取最后一个<li>元素

//$(" :not('')"):选取不是/非..元素
$("li:not('.c1')")    //选取class不为c1的<li>标签元素集合,多个选项用逗号“,”隔开

//$(" :even"):选取标签索引值为偶数的元素
$("li:even")          //获取<li>标签索引值为偶数的元素

//$(" :odd"):获取标签索引值为奇数的元素
$("li:odd")           //选取<li>标签的索引值为奇数数的元素

//$(" :eq(index)"):选取标签索引值为index的元素
$("li:eq(2)")         //选取<li>标签索引值为2的元素

//$(" :gt(index)"):选取标签索引值大于index的元素
$("li:gt(2)")         //选取<li>标签索引值大于2的元素

//$(" :lt(index)"):选取标签索引值小于index的元素
$("li:lt(2)")         //选取<li>标签的索引值小于2的元素

//$(" :focus"):选取焦点元素

我们也可以将其放在括号外面当方法用:

$("").first()           //选取第一个元素
$("").parent()          //选取父亲元素
$("").eq(index)         //选取索引值等于index的元素
$("").hasClass('xxx')   //判断某个对象是否有xxx类

3.3.2 内容过滤选择器

$("div:contains('xxx')")      //选取所有内容包含xxx文本的<div>元素
$(":empty")                   //选取所有内容为空的标签
$("div:has(selector)")        //选取含有选择器所匹配的<div>元素
$(":parent")                  //选取所有含有子元素或者文本的父元素。

3.3.3 可见性过滤选择器

$("li:hidden")       //选取所有不可见<li>元素,即style="display:none;"。或type为hidden的元素
$("li:visible")      //选取所有可见<li>元素

3.3.4 属性过滤选择器

$("div[id]")                //选取所有含有id属性的<div>元素
$("div[id='d']")            //选取id属性值为d的<div>元素,也可以写成$("div#d"),同样的$("div.classname")为获取class为classname的<div>元素
$("div[id!='d']")           //选取id属性值不等于d的<div>元素
$("div[id^='d']")           //选取id属性值以d开头的<div>元素
$("div[id$='d']")           //选取id属性值以d结尾的<div>元素
$("div[id*='d']")           //选取id属性值包含d字段的<div>元素
$("input[id][name$='man']") //多属性选过滤,同时满足两个属性的条件的元素
$("div[class~='xxx']")      //获取具有多个空格分隔的class值,其中一个值等于xxx的<div>元素

3.3.5 状态过滤选择器

$("input:enabled")    //选取可用的<input>元素
$("input:disabled")   //选取不可用的<input>元素
$("input:checked")    //选取选中的<input>元素
$("option:selected")  //选取选中的<option>元素

3.4 表单选择器

$(":input")      //选取所有<input>,<textarea>,<select>和<button>元素
$(":text")       //选取所有的单行文本框,$(":text") 等价于$("[type=text]"),推荐使用$("input:text")效率更高,下同
$(":password")   //选取所有密码框
$(":radio")      //选取所有单选按钮
$(":checkbox")   //选取所有复选框
$(":submit")     //选取所有提交按钮
$(":reset")      //选取所有重置按钮
$(":button")     //选取所有button按钮
$(":file")       //选取所有文件域

3.5 其他

$(document)         //文档对象
$(this)             //获取触发事件的当前HTML元素

 更多可参考:http://www.runoob.com/jquery/jquery-ref-selectors.html

四 元素操作

jQuery基础语法中的行为(action)包含很多内容,比如:读取标签内容,设置CSS样式,绑定事件响应代码、jQuery动画等。我们将前两种合并为元素操作,详细内容如下。

4.1 内容与属性操作

.text()      //设置或返回所选元素的文本内容。用作设置时,将设置值作为参数传递给它,下同
.html()      //设置或返回所选元素的内容(包括HTML标记)
.val()       //设置或返回表单字段的值

.attr('attr_name')            //设置或返回标记的某属性。用作设置时,将设置值作为最后一个参数传递给它,下同
.removeAttr('attr_name')      //删除标记的某属性
.prop()                       //设置或返回标记的某属性
.removeProp()                 //删除标记的某属性
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">

</head>

<body>
    <p id="d1"><b>这是段落中的粗体文本</b></p>
    <p><input type="text" id="d2" value="用户名"></p>
    <p><a href="http://www.baidu.com" id="d3">百度</a></p>
    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        var textValue = $("#d1").text();
        console.log(textValue);   //这是段落中的粗体文本
        var htmlValue = $("#d1").html();
        console.log(htmlValue);   //<b>这是段落中的粗体文本</b>
        var inputValue = $("#d2").val();
        console.log(inputValue);  //用户名
        var attrValue = $("#d3").attr("href");
        console.log(attrValue);   //http://www.baidu.com
    </script>
</body>
</html>
获取内容与属性
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">

</head>

<body>
    <p id="d1"><b>这是段落中的粗体文本</b></p>
    <p><input type="text" id="d2" value="用户名"></p>
    <p><a href="http://www.baidu.com" id="d3">百度</a></p>
    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        $("#d1").text("这是修改后段落中的斜体文本");
        $("#d1").html("<i>这是修改后段落中的斜体文本</i>");
        $("#d2").val("joe");
        $("#d3").attr("href","https://www.qq.com");
        $("#d3").text("腾讯");
    </script>
</body>
</html>
设置内容与属性
prop()函数的结果:

      1.如果有相应的属性,返回指定属性值。

      2.如果没有相应的属性,返回值是空字符串。

attr()函数的结果:

      1.如果有相应的属性,返回指定属性值。

      2.如果没有相应的属性,返回值是 undefined。

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

对于HTML元素我们自己自定义的DOM属性,在处理时,使用 attr 方法。

具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop()
attr和prop的区别

另外,它们都拥有回调函数。回调函数有两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

</head>

<body>

    <p id="d1">这是一个段落</p>
    <p><a href="http://www.baidu.com" id="d2">百度</a></p>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        // html()、var()与之类似
        $("#d1").text(function(i,origText){
            console.log(i,origText);  //0 "这是一个段落"
            return "这是一个段落,但是是新的。。。";
        })

        $("#d2").attr("href",function (i,origText) {
            console.log(i,origText);  //0 "http://www.baidu.com"
            return "https://www.qq.com";
        })

        $("#d2").text("腾讯");
    </script>
</body>
</html>
回调函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

</head>

<body>
    <p id="d1">段落1</p>
    <p id="d2">段落2</p>
    <p id="d3">段落3</p>
    <p id="d4">段落4</p>
    <p id="d5">段落5</p>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        // 方式一:循环"可迭代对象"   $.each(arr,funtion(){})
        li = ['a','b','c','d','e'];
        object = {"name":"joe","age":18};
        $.each(li,function (i,j) {
            console.log(i);              //指代索引值
            console.log(j);              //指代值
        });
        $.each(object,function (i,j) {
            console.log(i);              //指代key
            console.log(j);              //指代value
        });

        // 方式二:元素列表循环
        /*$(selector).each(function () {
            需要执行的操作;  //选择器中的所有元素均执行该操作
        })*/
        $("p").each(function(){
            if ($(this).html() == "段落3"){
//                return;         //仅结束当前元素动作,或者return true;
                return false;   //结束后面所有元素的动作
            }
            console.log($(this).html());
        });
    </script>
</body>
</html>
jQuery的循环方式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        input{
            margin-top: 10px;
        }
        button{
            margin-left: 15px;
        }
        .select_all{
            margin-left: 0px;
        }
    </style>
</head>
<body>
    <form>
        <input type="radio">&nbsp;选项一<br>
        <input type="radio">&nbsp;选项二<br>
        <input type="radio">&nbsp;选项三<br>
        <input type="radio">&nbsp;选项四<br>
        <input type="radio">&nbsp;选项五<br>
    </form>
    <br>
    <button class="select_all" onclick="select_all()">全选</button>
    <button class="select_reverse" onclick="select_reverse()">反选</button>
    <button class="cancel" onclick="cancel()">取消</button>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>

        function select_all() {
            $(":radio").prop("checked",true);
        }

        function select_reverse(){
            $(":radio").each(function () {
               $(this).prop("checked", !$(this).prop("checked"));     //一句话搞定,取反
//                if($(this).prop("checked")==false){
//                    $(this).prop("checked",true);
//                } else {
//                    $(this).prop("checked",false);
//                }
            })
        }
        function cancel() {
            $(":radio").prop("checked",false);
        }
    </script>
</body>
</html>
示例1--全选&反选&取消

4.2 添加、删除、替换、复制元素

$("<p>") or $("<p></p>")    //创建一个标签对象

.append()        //在父标记的最后部分插入标记
.prepend()       //在父元素的最前面部分插入标记
.after()         //紧随某元素的后面插入标记
.before()        //在某元素之前插入标记

.remove()        //删除标记,同时删除它的所有子标记
.empty()         //清空标记内容,但不删除标记本身

.replaceWith()   //替换标记

.clone()         //复制标记
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="d1">
        <P id="p1">段落1</P>
        <P id="p2">段落2</P>
        <P id="p3">段落3</P>
        <P id="p4">段落4</P>
    </div>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        //方式一
        var $newTag = $("<p>");
        $newTag.html("我是一个新的段落");
        $newTag.prop("id","new-p");

        //方式二
//        var newTag = document.createElement("p");     //使用时注意名字的修改
//        newTag.innerHTML = "我是一个新的段落";
//        newTag.setAttribute("id","new-p");


//        $("#d1").append($newTag);  //如果需要添加多个新元素,用逗号隔开即可
//        $("#d1").prepend($newTag);
//        $("#p4").after($newTag);
//        $("#p1").before($newTag);

//        $("#p1").remove();
//        $("#p2").empty();

//        $("#p1").replaceWith($newTag);
//        var $newTag2 = $("#p1").clone();
//        $("#d1").append($newTag2);
    </script>
</body>
</html>
实操演练
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        [type="button"]{
            width: 25px;
            line-height: 20px;
            margin-top: 5px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="item">
            <input type="button" value="+" onclick="add(this);">
            <input type="text">
        </div>
    </div>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>

//        var $clone_obj=$(self).parent().clone();  // $clone_obj放在这个位置可以吗?不可以,无self参数
//        var $clone_obj = $("[value='+']").parent().clone();  //这种方式只能进行一次克隆操作。
        function add(self){
//            var $clone_obj = $(".outer .item").clone();    //会一变二,二变四的增加,因为其克隆了所有的item标签
            var $clone_obj = $(self).parent().clone();
            $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
            $(self).parent().parent().append($clone_obj);
//            console.log($clone_obj);
        }
        function removed(self){
            $(self).parent().remove()
        }

    </script>
</body>
</html>
示例--复制样式条

4.3 CSS操作

.addClass(class|fn)          //向被选元素添加一个或多个类
.removeClass(class|fn)       //从被选元素删除一个或多个类
.toggleClass(class|fn)       //对被选元素进行添加/删除类的切换操作
.css(name|pro|[,val|fn])     //设置或返回样式属性

//位置
.offset([coordinates])       //设置或返回被选元素相对于文档的偏移坐标
    返回偏移坐标:$(selector).offset()
    设置偏移坐标:$(selector).offset({top:value,left:value})
    使用函数设置偏移坐标:$(selector).offset(function(index,currentoffset))
    
.position()                  //返回第一个匹配元素的位置(相对于它的父元素)        
    语法:$(selector).position()
    
.scrollTop([val])            //设置或返回被选元素的垂直滚动条位置
    返回垂直滚动条位置:$(selector).scrollTop()
    设置垂直滚动条位置:$(selector).scrollTop(position)    //position:规定以像素为单位的垂直滚动条位置。

$("").scrollLeft([val])      //设置或返回被选元素的水平滚动条位置
    用法与scrillTop一致

//尺寸
.height([val|fn])
.width([val|fn])
.innerHeight()
.innerWidth()
.outerHeight([soptions])
.outerWidth([options])

可参考:jQuery HTML / CSS 方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <P id="p1">这是一个段落</P>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        $("#p1").css("background-color","yellow");     //设置一个
        $("#p1").css({"font-size":"30px","color":"red"});     //设置多个
    </script>

</body>
</html>
实操演练
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0 auto;
            padding: 0;
        }
        input{
            width: 50px;
            height: 30px;
            line-height: 25px;
            text-align: center;
            font-size: 16px;
        }
        .c1{
            width: 80%;
            height: 1000px;
        }
        .shade{
            position: fixed;
            width: 80%;
            top: 0;
            bottom: 0;
            left:10%;
            right: 10%;
            background-color: gray;
            opacity: 0.5;
        }
        .models{
            position: fixed;
            width: 300px;
            height: 400px;
            top: 50%;
            left:50%;
            margin-left:-150px;
            margin-top: -200px;
            background-color: olivedrab;
            opacity: 0.5;
        }
        .key2{
            position: absolute;
            bottom: 0;
            right: 0;
        }
        .hide{
            display: none;
        }

    </style>
</head>
<body>
    <div class="c1">
        <input type="button" class="key1" value="点击">
    </div>
    <div class="shade hide handle"></div>
    <div class="models hide handle">
        <input type="button" class="key2" value="返回">
    </div>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>

//        方式一:通过标签直接操作,事件后面会学习
        $(".key1").click(function () {
            $(".handle").removeClass("hide");
        })
        $(".key2").click(function () {
            console.log($(".handle"));
            $(".handle").addClass("hide");
        })

//        方式二:通过导航查找,后面会学习
//        $(".key1").click(function () {
//            $(this).parent().siblings().removeClass("hide");
//        })
//        $(".key2").click(function () {
//           $(this).parent().addClass("hide").prev().addClass("hide");
//        })

    </script>

</body>
</html>
示例1--模态对话框
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        *{
            margin: 0 auto;
        }
        .div{
            width: 80%;
            height: 2000px;
            background-color: #7A77C8;
            color: white;
        }
        .returnTop{
            height: 40px;
            width: 80px;
            background-color: darkgray;
            position: fixed;
            right: 10px;
            bottom: 10px;
            color: white;
            line-height: 40px;
            text-align: center;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
    <div class="div">页面顶部</div>
    <div class="returnTop hide" onclick="returnTop();">返回顶部</div>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        window.onscroll = function(){
            var current = $(window).scrollTop();
            console.log(current)
            if (current>100){
                $(".returnTop").removeClass("hide")
            }
            else {
                $(".returnTop").addClass("hide")
            }
        }
        function returnTop(){
            $(window).scrollTop(0)
        }
    </script>
</body>
</html>
实例2--返回页面顶部

五 事件响应

jQuery封装了对HTML事件的响应处理,每个事件都被定义成一个jQuery行为。用jQuery响应HTML事件的基本语法如下:

$(selector).EVENT(function(){
    //事件处理代码
    });

其中ENVET是HTML事件除去开头“on”字样的名字,比如:对于HTML的“onclick”事件在jQuery对应的事件为“click”。另外,jQuery中有一个特殊的事件:

$(document).ready()

该方法用于响应文档已全部加载的事件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button class="b1">按钮</button>

    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
//        $(document).ready(function () {
//            alert("文档已经全部加载完成")
//        });

        // 上述方式我们可以简写成如下:
        $(function () {
            alert("文档已经全部加载完成")
        });

        $(".b1").mouseleave(function (){
            alert("鼠标已经离开按钮")
        })
    </script>
</body>
</html>
一个示例

常见的HTML事件都有相应的jQuery行为,具体的我们可以参考:http://www.runoob.com/jquery/jquery-ref-events.html

上述响应事件的方式,有一个问题,我们先来看一个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="test">
        <button class="new" id="newclick">新建一行数据</button>
        <ul class="li">
            <li>原先的HTML元素<button class="deleteclick">Delete</button></li>
        </ul>
    </div>

    <script src="jquery-3.2.1.js"></script>
    <script>
        $("#newclick").click(function(){
            $(".li").append('<li>动态click添加的HTML元素<button class="deleteclick">Delete</button></li>');
        });
        $(".deleteclick").click(function(){
            $(this).parent().remove();   // 动态添加的<li>元素通过.click方式不能删除,因为该方式不能让动态添加的元素绑定事件
        });
    </script>
</body>
</html>
View Code

通过上述例子我们可以发现,对于由 jQuery 动态生成的元素,如上例中用 jQuery 给元素添加 <li>元素,不能直接绑定常用的事件,如 click。

因为这些元素属于动态生成,除非采用 noclick 内联的形式。那么解决办法是使用 live 和 on 事件方法。

注意:jquery 1.7.2 之后的版本不建议使用 live。下面我们以on事件进行说明

on() 方法定义和用法

on() 方法在被选元素及子元素上添加一个或多个事件处理程序。

自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。该方法给 API 带来很多便利,我们推荐使用该方法,它简化了 jQuery 代码库。

注意:使用 on() 方法添加的事件处理程序适用于当前及未来的元素(比如由脚本创建的新元素)。

提示:如需移除事件处理程序,请使用 off() 方法。

提示:如需添加只运行一次的事件然后移除,请使用 one()方法。

on() 方法语法

$(selector).on(event,childSelector,data,function)
    //参数说明:
    //event:必需。规定要从被选元素移除的一个或多个事件或命名空间。由空格分隔多个事件值,也可以是数组。必须是有效的事件。
    //childSelector:可选。规定只能添加到指定的子元素上的事件处理程序(且不是选择器本身,比如已废弃的 delegate() 方法)。
    //data:可选。规定传递到函数的额外数据。
    //function:可选。规定当事件发生时运行的函数。

现在我们将刚刚的例子做一下修改:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>jQuery中on()和click()的区别</h3>
    <p>点击生成新按钮。NewOn生成的Delete按钮行为用on()实现,NewClick生成的Delete按钮行为用click()实现。</p>
    <div class="test">
        <button class="new" id="newon">NewOn</button>
        <button class="new" id="newclick">NewClick</button>
        <ul class="li">
            <li>原先的HTML元素on<button class="deleteon">Delete</button></li>
            <li>原先的HTML元素click<button class="deleteclick">Delete</button></li>
        </ul>
    </div>
    <script src="jquery-3.2.1.js"></script>
    <script>
        $("#newon").click(function(){
            $(".li").append('<li>动态on添加的HTML元素<button class="deleteon">Delete</button></li>');
        });
        $("#newclick").click(function(){
            $(".li").append('<li>动态click添加的HTML元素<button class="deleteclick">Delete</button></li>');
        });
        $(".li").on('click', ".deleteon", function(){
            $(this).parent().remove();   //动态生成的只能通过on方式才能删除
        });
        $(".deleteclick").click(function(){
            $(this).parent().remove();
        });
    </script>
</body>
</html>
修改后的例子
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
    .c1 {
        font-size:150%;
        color:red;
    }
    </style>
</head>
<body>
    <p>移动鼠标到这里看看有什么变化!!!</p>
    <script src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function(){
            $("p").on("mouseover mouseout",function(){
                $("p").toggleClass("c1");
            });
        });
    </script>
</body>
</html>
添加多个事件处理程序
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button>点我</button>
    <script src="jquery-3.2.1.js"></script>
    <script>
        function func1(event) {
            alert(event.data.msg);
        };

        $(document).ready(function(){
            $("button").on("click", {msg: "输出内容"}, func1)
        });
    </script>
</body>
</html>
向函数传递数据--data的使用
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .outer{
            width: 500px;
            height: 500px;
            line-height: 50px;
            font-size: 30px;
            text-align: center;
            position: absolute;
            border: 1px solid red;
        }
        #title{
            height: 50px;
            color: white;
            background-color: #336699;
        }
        #content{
            height: 450px;
            background-color: #cccccc;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div id="title">标题</div>
        <div id="content">内容</div>
    </div>

    <script type="text/javascript" src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function(){
//        $(function(){
            // 页面加载完成之后自动执行
            $("#title").mouseover(function(){
                $(this).css("cursor","move");
            }).mousedown(function(e){
                console.log($(this).offset());
                var _event = e || window.event;
                // 原始鼠标横纵坐标位置
                var old_x = _event.clientX;
                var old_y = _event.clientY;
//                console.log(old_x,old_y);

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

                $(this).bind('mousemove', function(e){
                    var _new_event = e || window.event;
                    var new_x = _new_event.clientX;
                    var new_y = _new_event.clientY;

                    var x = parent_left + (new_x - old_x);
                    var y = parent_top + (new_y - old_y);

                    $(this).parent().css('left',x+'px');
                    $(this).parent().css('top',y+'px');
                })
            }).mouseup(function(){
                $(this).unbind('mousemove');
            });
        })
    </script>
</body>
</html>
示例1--面板拖动
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>bigger</title>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        .outer{
            height: 350px;
            width: 350px;
            border: dashed 5px cornflowerblue;
        }
        .outer .small_box{
            position: relative;
        }
        .outer .small_box .float{
            height: 175px;
            width: 175px;
            background-color: darkgray;
            opacity: 0.4;
            fill-opacity: 0.4;
            position: absolute;
            display: none;

        }
        .outer .big_box{
            height: 400px;
            width: 400px;
            overflow: hidden;
            position:absolute;
            left: 360px;
            top: 0px;
            z-index: 1;
            border: 5px solid rebeccapurple;
            display: none;
        }
        .outer .big_box img{
            position: absolute;
            z-index: 5;
        }

    </style>
</head>
<body>
    <div class="outer">
        <div class="small_box">
            <div class="float"></div>
            <img src="kobe1.jpg">
        </div>
        <div class="big_box">
            <img src="kobe1.jpg">
        </div>
    </div>

<script src="jquery-3.2.1.js"></script>
<script>
    $(function(){
          $(".small_box").mouseover(function(){
              $(".float").css("display","block");
              $(".big_box").css("display","block")
          });

          $(".small_box").mouseout(function(){
              $(".float").css("display","none");
              $(".big_box").css("display","none")
          });

          $(".small_box").mousemove(function(e){
              var _event=e || window.event;
              var float_width=$(".float").width();
              var float_height=$(".float").height();
              console.log(float_height,float_width);
              var float_height_half=float_height/2;
              var float_width_half=float_width/2;
              console.log(float_height_half,float_width_half);
              var small_box_width=$(".small_box").height();
              var small_box_height=$(".small_box").width();

              // 鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
              var mouse_left=_event.clientX-float_width_half;
              var mouse_top=_event.clientY-float_height_half;

              if(mouse_left<0){
                  mouse_left=0
              }else if (mouse_left>small_box_width-float_width){
                  mouse_left=small_box_width-float_width
              }

              if(mouse_top<0){
                  mouse_top=0
              }else if (mouse_top>small_box_height-float_height){
                  mouse_top=small_box_height-float_height
              }

              $(".float").css("left",mouse_left+"px");
              $(".float").css("top",mouse_top+"px")

              var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
              var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);

              console.log(percentX,percentY)

              $(".big_box img").css("left", -percentX*mouse_left+"px")
              $(".big_box img").css("top", -percentY*mouse_top+"px")
          })
     })
</script>
</body>
</html>
示例2--放大镜

六 标记遍历

与JavaScript遍历DOM树的一系列类相对位置的函数(nextSibing、parentNode等)类似,jQuery也提供了一系列对选择器所定位的元素进行前后遍历的行为,常用的标记遍历如下:

//祖先
.parent()            //返回被选元素的直接父元素
.parents()           //返回被选元素的所有祖先元素,它一路向上直到文档的根元素(<html>)
.parentUntil()       //返回介于两个给定元素之间的所有祖先元素

//后代
children()           //返回被选元素的所有直接子元素
find()               //返回被选元素的后代元素,一路向下直到最后一个后代

//同胞
.siblings()          //返回被选元素的所有同胞元素
.next()              //返回被选元素的下一个同胞元素
.nextAll()           //返回被选元素的所有跟随的同胞元素
.nextUntil()         //返回介于两个给定参数之间的所有跟随的同胞元素

.prev()              //返回被选元素的上一个同胞元素
.prevAll()           //返回被选元素的所有前面的同胞元素
.prevUntil()         //返回介于两个给定参数之间的所有前面的同胞元素

//过滤(前面选择器时已提)
.first()             //返回被选元素的首个元素
.last()              //返回被选元素的最后一个元素。
.eq()                //返回被选元素中带有指定索引号的元素。
.filter()            //允许规定一个标准。不匹配这个标准的元素会被从集合中删除,匹配的元素会被返回
.not()               //返回不匹配标准的所有元素,not()方法与filter()相反
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0 auto;
            padding: 0;
        }
        .outer{
            width: 80%;
            height: 315px;
            margin-top: 20px;
        }
        #left{
            float: left;
            width: 20%;
            height: 315px;
            background-color: #7A77C8;
        }
        #right{
            float: left;
            width: 80%;
            height: 315px;
            background-color: blueviolet;
            font-size: 30px;
            text-align: center;
            line-height: 315px;
        }
        .title{
            font-size: 20px;
            height: 30px;
            line-height: 30px;
            padding-left: 20px;
            background-color: blue;
            margin-top: 5px;
        }
        .menu-list{
            list-style-type: none;
            padding-left: 20px;
            color: white;
            line-height: 25px;
        }
        .hide{
            display: none;
        }

    </style>
</head>
<body>
    <div class="outer">
        <div id="left">
            <div class="menu">
                <div class="title">手机</div>
                <ul class="menu-list">
                    <li>华为</li>
                    <li>一加</li>
                    <li>小米</li>
                </ul>
            </div>
            <div class="menu">
                <div class="title">电视</div>
                <ul class="menu-list hide">
                    <li>长虹</li>
                    <li>康佳</li>
                    <li>海信</li>
                </ul>
            </div>
            <div class="menu">
                <div class="title">电脑</div>
                <ul class="menu-list hide">
                    <li>联想</li>
                    <li>华硕</li>
                    <li>华为</li>
                </ul>
            </div>
        </div>
        <div id="right">内容</div>
    </div>
    <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>

        $(".menu .title").click(function () {
            // $(this).next().removeClass("hide").parent().siblings().children(".menu-list").addClass('hide');
            $(this).next().removeClass("hide");
            $(this).parent().siblings().children(".menu-list").addClass("hide");
        })

    </script>
</body>
</html>
示例1--左侧菜单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 10px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
            padding: 0px 5px;
        }
        .content{
            background-color: yellowgreen;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }
        .current{
            background-color: darkgray;
            color: red;
            border: 1px solid gray ;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li attr1="c1" class="current" onclick="tab(this);">菜单一</li>
              <li attr1="c2" onclick="tab(this);">菜单二</li>
              <li attr1="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="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
           function tab(self){
               var index = $(self).attr("attr1");
               $("#"+index).removeClass("hide").siblings().addClass("hide");
               $(self).addClass("current").siblings().removeClass("current");
           }
    </script>
</body>
</html>
示例2--tab切换

七 jQuery特效

除了对HTML、CSS、JavaScript相关行为的简单封装,jQuery还提供了一些用JavaScript实现难度较大的动画特效行为。

7.1 显示隐藏(show/hide)

.toggle()   //可以使用toggle()方法来切换 hide()和show()方法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>hello world</p>
    <button id="hide">隐藏</button>
    <button id="show">显示</button>
    <button id="toggle">切换</button>
    <script src="jquery-3.2.1.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(1000);
            });
        })
    </script>
</body>
</html>
View Code

7.2 滑动(slide)

.slideDown()         //用于向下滑动元素
.slideUp()           //用于向上滑动元素
.slideToggle()       //可以在slideDown()与slideUp()方法之间进行切换
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.2.1.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;
            height: 50px;
            line-height: 50px;
            background-color: gray;
            border:solid 1px red;
            padding: 5px;
        }
    </style>
</head>
<body>

    <div id="content">hello world</div><br>
    <button id="slideDown">出现</button>
    <button id="slideUp">隐藏</button>
    <button id="slideToggle">toggle</button>

</body>
</html>
View Code

7.3 淡入淡出(fadeIn/fadeOut)

.fadeIn()       //用于淡入已隐藏的元素
.fadeOut()      //用于淡出可见元素
.fadeToggle()   //可以在fadeIn()与fadeOut()方法之间进行切换
.fadeTo(speed,opacity,callback)       //渐变为给定的不透明度。其中speed可以取值为slow、fast或毫秒,opacity值介于0与1之间,callback为动作完成后需要回调的函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.2.1.js"></script>
    <script>
    $(document).ready(function(){
        $("#in").click(function(){
            $("#content").fadeIn(1000);
        });
        $("#out").click(function(){
            $("#content").fadeOut(1000);
        });
        $("#toggle").click(function(){
            $("#content").fadeToggle(1000);
        });
        $("#fadeto").click(function(){
            $("#content").fadeTo(1000,0.4);
        });
    });
    </script>
    <style>
        #content{
            text-align: center;
            height: 50px;
            line-height: 50px;
            background-color: gray;
            border:solid 1px red;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="content">hello world</div><br>
    <button id="in">fadein</button>
    <button id="out">fadeout</button>
    <button id="toggle">fadetoggle</button>
    <button id="fadeto">fadeto</button>
</body>
</html>
View Code

7.4 动画(animate)

.animate({params},speed,callback)       //自定义动画效果。
    //params:可以是任意的CSS属性必需的 params 参数定义形成动画的 CSS 属性
    //speed:可选的。规定效果的时长,它可以取以下值:"slow"、"fast" 或毫秒
    //callback:可选的。是动画完成后所执行的函数名称
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("div").animate({
                    left:'300px',
                    opacity:'0.6',
                    height:'200px',
                    width:'200px'
                });
            });
        });
    </script>
    <style>
        .d1{
            position: absolute;
            background-color: gray;
            width: 100px;
            height: 100px;
            margin-top: 10px;
        }
    </style>
</head>

<body>

    <button>开始动画</button>
    <div class="d1"></div>

</body>
</html>
View Code

animate() 方法可以操作所有 CSS 属性吗?

是的,几乎可以!不过,需要记住一件重要的事情:当使用 animate() 时,必须使用 Camel 标记法书写所有的属性名。比如:必须使用 paddingLeft 而不是 padding-left,使用 marginRight 而不是 margin-right,等等。

注意:

默认情况下,所有的 HTML 元素有一个静态的位置,且是不可移动的。

如果需要改变,我们需要将元素的 position 属性设置为 relative, fixed, 或 absolute!

7.5 停止动画(stop)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function(){
            $(".start").click(function(){
                $(".content").slideDown(5000);
            });
            $(".stop").click(function(){
                $(".content").stop();
            });
        });
    </script>

    <style>
        .content {
            padding:50px;
            background-color: gray;
            font-size: 30px;
            text-align: center;
            display:none;
            margin-top: 10px;
        }
    </style>
</head>
<body>

    <button class="start">开始滑动</button>
    <button class="stop">停止滑动</button>
    <div class="content">Hello world!</div>

</body>
</html>
View Code

7.6 回调函数

回调函数在当前动画 100% 完成之后执行。

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

    <style>
        #content{
            text-align: center;
            height: 50px;
            line-height: 50px;
            background-color: gray;
            border:solid 1px red;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="content">hello world</div><br>
    <button>隐藏</button>

    <script src="jquery-3.2.1.js"></script>
    <script>
        $("button").click(function(){
            $("#content").hide(1000,function(){
                alert("已被隐藏!!!");
            })
        })
    </script>
</body>
</html>
View Code

没有回调函数,警告框会在隐藏效果完成前弹出:

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

    <style>
        #content{
            text-align: center;
            height: 50px;
            line-height: 50px;
            background-color: gray;
            border:solid 1px red;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="content">hello world</div><br>
    <button>隐藏</button>

    <script src="jquery-3.2.1.js"></script>
    <script>
        $("button").click(function(){
            $("#content").hide(1000);
            alert("已被隐藏!!!");
        })
    </script>
</body>
</html>
View Code

八 插件机制

8.1 核心方式

jQuery.extend(object)      //为jQuery 添加一个静态方法。
jQuery.fn.extend(object)   //为jQuery实例添加一个方法。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script src="jquery-3.2.1.js"></script>
    <script>
        $.extend({
            min:function (a,b) {
                return a<b? a:b;
            },
            max:function (a,b) {
                return a>b? a:b;
            }
        });
        console.log($.min(1,2));
        console.log($.max(1,2));
    </script>
</body>
</html>
jQuery.extend(object)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>

    </style>
</head>
<body>

    <input type="radio">选择一
    <input type="radio">选择二
    <input type="radio">选择三
    <input type="radio">选择四<br><br>
    <button class="all">全选</button>
    <button class="cancel">取消</button>

    <script src="jquery-3.2.1.js"></script>
    <script>
        $.fn.extend({
            check:function () {
                return this.each(function () {
                    this.checked = true;
                })
            },
            uncheck:function () {
                return this.each(function () {
                    this.checked = false;
                })
            }
        })
        $(".all").click(function () {
            $(":radio").check();
        })
        $(".cancel").click(function () {
            $(":radio").uncheck();
        })
    </script>

</body>
</html>
jQuery.fn.extend(object)

8.2 定义作用域

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

(function(a,b){return a+b})(3,5)
    (function ($) { })(jQuery);
//相当于
    var fn = function ($) { };
    fn(jQuery);

8.3 默认参数

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

//step01 定义JQuery的作用域
(function ($) {
    //step03-a 插件的默认值属性
    var defaults = {
        prevId: 'prevBtn',
        prevText: 'Previous',
        nextId: 'nextBtn',
        nextText: 'Next'
        //……
    };
    //step06-a 在插件里定义方法
    var showLink = function (obj) {
        $(obj).append(function () { return "(" + $(obj).attr("href") + ")" });
    }

    //step02 插件的扩展方法名称
    $.fn.easySlider = function (options) {
        //step03-b 合并用户自定义属性,默认属性
        var options = $.extend(defaults, options);
        //step4 支持JQuery选择器
        //step5 支持链式调用
        return this.each(function () {
            //step06-b 在插件里定义方法
            showLink(this);
        });
    }
})(jQuery);
View Code

 

参考:http://www.cnblogs.com/yuanchenqi/articles/6070667.html

更多可参考:http://www.runoob.com/jquery/jquery-tutorial.html


posted @ 2018-09-20 09:29  Joe1991  阅读(116)  评论(0)    收藏  举报