admin管理员组

文章数量:1587994

完整的jquery中文文档请参见:jquery.cuishifeng

 

1. JQuery的简介

1)为何使用jQuery,jQuery解决了以下问题:

  • JavaScript代码书写繁琐、代码量大、代码复杂
  • 动画、开启定时器、定时器的清除、各种操作和处理事件等不好实现
  • 浏览器的兼容性

 

2)JavaScript和jQuery的区别

  • JavaScript是一门编程语言,用来编写客户端浏览器脚本
  • jQuery是javascript的一个库,包含多个可重用的函数,用来辅助我们简化javascript开发
  • jQuery能做的javascript都能做到,而javascript能做的事情,jQuery不一定能做到

 

3)执行时间不同

window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行

$(document).ready()是DOM结构绘制完毕后就执行,不必等到加载完毕。可以简写为$(function(){ alert(1) })

 

 

 

2.选择器

1)基本选择器

<script type="text/javascript">

    $(document).ready(function(){
        // id选择器
        $("#brother").css("display", "none");

        // 标签选择器
        $("a").css({"color": "red", "font-size": "24px"});

        // 类选择器
        $(".apple").css("background", "green");

        // 通配符选择器,这种方法使用不多
        $("*").css("padding", "0");
        $("*").html("");
    });
</script>

 

2)层级选择器

<script type="text/javascript">

    $(document).ready(function(){
        // 后代选择器
        $("div p").css("color", "red");

        // 子代选择器
        $("#box2 > p").css({"color": "yellow", "font-size": "24px"});

        // 毗邻选择器,匹配所有紧接着选中元素的兄弟
        $("#father + p").css("font-size", "50px");

        // 兄弟选择器
        $("#father ~ p").css("padding", "20px 20px");
        
        // 获取第一个元素
        $("li:first").css("font-size", "10px");
        
        // 获取第一个元素
        $("li:last").css("font-size", "45px");

        // 获取第n个元素
        $("li:eq(n)").css("color", "blue");
        
    });
</script>

 

3)基本筛选器

<script type="text/javascript">

    $(document).ready(function(){
        // 获取第一个:first
        $("li:first").css("font-size", "10px");
        
        // 获取最后一个元素
        $("li:last").css("font-size", "45px");

        // 获取第n个元素,这个方法使用的最多
        $("li:eq(n)").css("color", "blue");
        
        // 获取奇数索引的元素
        $("li:odd").css("color", "white");
        
        // 获取偶数索引的元素
        $("li:even").css("font-size", "70px");

        // 获取大于某个索引的元素
        $("li:gt(3)").css("font-size", "30px");

        // 获取小于某个索引的元素
        $("li:lt(3)").css("font-size", "77px");   
     
    });
</script>

:first 选择众多相同元素当中的第一个,例$("li :first").css("color", "green")

:last 选择出最后一个

:not(selector) 非

:even 选择出索引为偶数的结果

:odd 选择出索引为奇数的结果

:eq(index) 选择出固定索引值的结果

:gt(index) 选择出大于某索引值的结果

:lt(index) 选择出小于某索引值的结果

:header 选出标题类型,例如<h1></h1>

 

4)内容筛选器

:contains(text) 通过内容进行筛选,例$("div :contains('Steve')")

:empty 内容为空的标签

:has(selector) 选出包含某个标签的,例$("div:has(p)").addClass("test"),找出div标签中有p标签的

 

5)可见性筛选器

:hidden 隐藏的

:visible 可见的

 

6)属性筛选器

<script type="text/javascript">

    $(document).ready(function(){
        // 标签名[属性名] 查找所有含有id属性的该标签名的元素
        $("li[id]").css("color", "red");
        
        // [attr=value] 匹配给定的属性是某个特定值的元素
        $("li[class=what]").css("font-size", "30px");

        // [attr!=value] 匹配所以不包含指定的属性,或者属性不等于特定值的元素
        $$("li[class!=what]").css("color", "yellow");

        // 匹配给定的属性是以某些值开始的元素
        $("input[name^=username]").css("background", "red");

        // 匹配给定的属性是以某些值结束的元素
        $("input[name$=222]").css("background", "yellow");
        
        // 匹配给定的属性是以包含某些值的元素
        $("button[class*='btn']").css("background", "white");
    });
</script>

多个属性进行筛选用中括号进行分割,例$("input[id][name='man'")

 

7) 表单选择器

选取表单元素的简写形式,例,$(":checkbox")

:input

:text

:password

:radio

:checkbox

:submit

:image

:reset

:button

:file

 

8)表单对象属性

:enabled 查找所有表单对象中启用的元素

:disabled 查找所有表单对象中禁用的元素

:checked 查找所有选中的选项元素(复选框、单选框等,select中的option),对于select元素来说,获取选中推荐使用

:selected 查找所有选中的选项元素

 

 

 

3. 筛选器

1)过滤

<script type="text/javascript">
    // eq(index|-index), 获取第n个元素
    $("li").eq(1).css("fontSize","30px")

    // first() 获取第一个元素
    $("li").first().css("background", "red");
    
    // last 获取最后一个元素
    $("li").last().css("background", "black");

    // .parent()选择父元素
    $("span").parent(".p1").css({"width": "500px"});

    // .siblings()选择所有的兄弟元素
    $(".list").siblings("li").css("color", "red");

    // .find() 查找所有的后代元素
    $("div").find("button").css("background", "red");
</script>

 

2)查找

children([expr]) 取得一个包含匹配的元素集合中每一个元素的所有子元素的元素集合。可以通过可选的表达式来过滤所匹配的子元素,例$("div").children()。注意:parents()将查找所有祖辈元素,而children()之查找子元素,而不查找所有后代元素。

next([expr]) 获取满足条件的下一个元素

nextAll([expr]) 获取满足条件的以下所有元素

nextUtil([ele][.f]) 获取满足条件的所有元素,直到某个条件(不包含某条件),例$(".div1").nextUntil(".div4") ,不包含id为div4的标签元素

parent([expr]) 获取满足条件的父级元素

parents([expr]) 获取满足条件的所有父级元素,例$("p").parents()

parentsUntil([ele][.f]) 获取满足条件的父级元素,直到某个条件

prev([expr]) 获取满足条件的上一个元素

prevAll([expr]) 获取满足条件的所有之前的元素

prevUntil([ele][.f]) 获取满足条件的之前元素,直到某元素

siblings 获取满足条件的所有兄弟元素

find 搜索于指定表达式匹配的元素

 

 

 

4. jQuery的效果

1)show,显示隐藏的匹配元素,

语法:show(speed, callback)参数:

speed:三种预定速度之一的字符串("slow", "normal", "fast")或表示动画动画时长的毫秒值

callback:在动画完成时执行的函数,每个元素执行一次

 

2)hide,隐藏显示的元素

语法:hide(speed, callback)

可以通过show()和hide()方法,来动态控制元素的显示隐藏

 

3)toggle

如果元素是可见的,切换为隐藏的;如果元素是隐藏的,切换为可见的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>隐藏</title>
    <style type="text/css">
        #box{
            width: 200px;
            height: 200px;
            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">

        $("#btn").click(function(){
            $("#box").toggle("slow");
        })

    </script>
</html>

 

4)slideDown

通过高度变化来动态地显示所有匹配的元素,在显示完成后触发一个回调函数,用法和参数跟上面类似

 

5)slideUp

通过高度变化来动态地隐藏所有匹配的元素,在隐藏完成后触发一个回调函数

 

6)slideToggle

通过高度变化来切换所有元素的可见性,并在切换完成后可选地触发一个回调函数,跟toggle用法类似

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>隐藏</title>
    <style type="text/css">
        #box{
            width: 200px;
            height: 200px;
            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">

        $("#btn").click(function(){
            $("#box").slideToggle("slow");
        })

    </script>
</html>

 

7)fadeIn

通过不透明度的变化来实现所有匹配元素的淡入效果,并在动画完成后可选地触发一个回调函数。这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化

 

8)fadeOut

通过不透明度的变化来实现所有匹配元素的淡出效果,并在动画完成后可选地触发一个回调函数。这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>隐藏</title>
    <style type="text/css">
        #box{
            width: 200px;
            height: 200px;
            border: 1px solid red;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="box">

    </div>
    <button id="btn">显示/隐藏</button>

</body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">

        $("#box").mouseover(function(){
            $("#box").fadeOut(2000);
        })

        $("#btn").mouseenter(function(){
            $("#box").fadeIn(2000);
        })

    </script>
</html>

 

9)fadeTo

把所有匹配元素的不透明度以渐进方式调整到指定的不透明度,并在动画完成后可选地触发一个回调函数。

这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化。

 

10)fadeToggle

通过不透明度的变化来开关所有匹配元素的淡入和淡出效果,并在动画完成后可选地触发一个回调函数。

这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化。

 

11)animate

用于创建自定义动画的函数

语法:animate(params, [speed], [fn])

params:一组包含作为动画属性和终值的样式属性及其值的集合

speed:三中预定速度之一的字符串("slow", "normal", "fast")或表示动画时长的毫秒数值

fn:在动画完成时执行的函数,每个元素执行一次。

 

12)stop

停止所有在指定元素上正在进行的动画

stop([clearQueue], [goToEnd])

clearQueue:如果设置成true,则清空队列。可以立即结束动画。

gotoEnd:让当前正在执行的动画立即完成,并且重设show和hide的原始样式,调用回调函数等

 

13)delay

用来做延迟的操作

语法:delay(1000),一秒之后做后面的操作

 

右下角弹出广告

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>右下角弹出广告</title>
    <style type="text/css">
        #box{
            width: 330px;
            height: 480px;
            position: absolute;
            right: 10px;
            bottom: 0;
            display: none;
        }
        img{
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div id="box">
        <img src="mi.png">
    </div>

</body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#box").slideDown("normal").slideUp("fast").fadeIn(1000).click(function(){
                $(this).fadeOut(4000);
            })
        })
    </script>
</html>

 

tab菜单代码案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tab-Menu</title>
    <style>
        *{
            margin:0px;
            padding:0px;
        }
        .tab-outer{
            width:70%;
            background-color: gray;
            margin:0 auto;
            height:600px;
        }
        .menu{
            background-color:navajowhite;
        }
        .menu li{
            display:inline-block;
            height:30px;
            line-height:30px;
            cursor:pointer;
        }
        .content{
            background-color:violet;
            padding:50px;
            height:auto;
        }
        .current{
            background-color:aliceblue;
            color:red;
        }
        .hide{
            display:none;
        }
    </style>
</head>
<body>
    <div class="tab-outer">
        <ul class="menu">
            <li index="c1" class="current" onclick="Show(this);">菜单一</li>
            <li index="c2" onclick="Show(this);">菜单二</li>
            <li index="c3" onclick="Show(this);">菜单三</li>
        </ul>
        <div class="content">
            <div id="c1">内容一</div>
            <div id="c2" class="hide">内容二</div>
            <div id="c3" class="hide">内容三</div>
        </div>
    </div>

    <script src="jquery.js"></script>
    <script>
        function Show(arg){
            $(arg).addClass("current").siblings().removeClass("current");
            var index = $(arg).attr("index");
            $("#" + index).siblings().addClass("hide");
            $("#" + index).removeClass("hide");
        }
    </script>
</body>
</html>

 

 

 

5. 属性操作(属性CSS和文档处理)

1)属性操作

  • $("p").text() 获取文本,在括号中输入值可设置标签的文本内容
  • $("p").html() 获取到包含标签的文本内容
  • $(":radio").val() 获取value值
// 1. 获取单选框中的value值
$("input[type=radio]:checked").val();

// 2. 复选框中value值,仅仅获取第一个值
$("input[type=checkbox]:checked").val();

// 3. 下拉列表被选中的值
$("#timespan option:selected");

// 4. 设置单选的值
$("input[type=radio]").val(["111"]);
$("input[type=checkbox]").val(["b", "c"]);

// 5. 设置下拉列表选中的值,这里必须要用select
$("select").val(['3', '2']);

 

  • $(".test").attr("tab-index") 获取test样式下属性为tab-index的属性值,在attr输入第二个参数可设置对应的属性值,如要设置多个值,则需要放入字典中,如下例所示:$("img").attr({src : "logo.jpg", alt: "Test Image"});
  • $(".test").removeAttr("checked") 删除某标签下的属性
  • $("input[type='checkbox']").prop("checked", true) 获取在匹配的元素集中的第一个元素的属性值,如设定了第二个属性则赋值。尽量使用prop方式来操作属性值

 

checkbox的全选、取消、反选的代码案例:

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

    </style>
</head>
<body>
    <form>
        <div>
            <input type="button" value="全选" onclick="SelectAll();">
            <input type="button" value="取消" onclick="Cancel();">
            <input type="button" value="反选" onclick="Reverse();">
        </div>
        <table>
            <tr>
                <td><input type="checkbox" value="Basketball"></td>
                <td>篮球</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>足球</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>网球</td>
            </tr>
        </table>

    </form>

    <script src="jquery.js"></script>
    <script>
        function SelectAll(){
            $("table :checkbox").attr("checked", true);
        }
        function Cancel(){
            $("table :checkbox").prop("checked", false);
        }
        function Reverse(){
            var checkboxes = $("table :checkbox");
            for(var i = 0; i < checkboxes.length; i++){
                if($(checkboxes[i]).prop("checked") == false){
                    $(checkboxes[i]).prop("checked", true);
                }else{
                    $(checkboxes[i]).prop("checked", false);
                }
            }
        }
    </script>
</body>
</html>

 

2)CSS类

addClass(class) 添加CSS样式

removeClass(class) 移除CSS样式

$("#c1").css("backgroundColor", "gray") 设置css样式

 

 

 

6. 文档操作

1)插入操作

(1)父元素.append(子元素),追加某元素,父元素中添加新的元素

 $("#c1").append("<p>hello</p>") 在某标签后添加相应内容

如果插入的内容是当前页面中的某些元素,那么会将元素移动到插入的地方:

$("ul").append($("#app"));

(2) 子元素.appendTo(父元素) 住家到某元素,子元素添加到父元素

$("p").appendTo("div") 将某内容添加到某标签后

(3)在某标签前添加相应内容

$("ul").prepend("<li>我是第一个li元素</li>") 在某标签前添加相应内容

$("<li>我是第一个li元素</li>").prependTo($("ul")) 将某标签添加到某标签前

(4)after、before 

$("ul").after("<h3>我是一个三级标题</h3>");

$("ul").before("<h2>我是一个二级标题</h2>");

(5)insertAfter、insertBefore

$("<p>111</p>").insertAfter("ul");

$("<p>111</p>").insertBefore("ul");

 

2)复制操作

clone()克隆匹配的DOM元素并且选中这些克隆的副本,如果clone(true),则副本与真身一样具有事件处理能力

$('button').click(function(){
    $(this).clone(true).insertAfter(this);
})

 

3)替换

replaceWith() :将所有匹配的元素替换成指定的HTML或DOM元素

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

// 将所有h5标题标签替换成id为app的dom元素
$('h5').replaceWith($('#app'));

replaceAll():用匹配的元素替换到所有selector匹配到的元素

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

 

4)删除操作

remove():删除节点后,事件也会删除(简而言之,删除了整个标签)

$("ul").remove();

detach():删除节点后,事件会保留

$('button').detach();

empty() 只是清空了被选元素的内容

$('ul').remove();

 

 

 

7. 位置属性

1)position,获取匹配元素相对父元素的偏移位置

 

2)offset,获取匹配元素在当前窗口的相对偏移,返回的对象包含两个整形属性:top和left

$(“p”).offset();
$("div").offset().left;
$("p").offset().top;

 

3)scrollTop,获取匹配元素相对滚动条顶部的偏移,文档被卷起的像素值

 

4)scrollLeft,获取匹配元素相对滚动条左侧的偏移,文档被卷起的像素值

$(document).scrollTop();
$(document).scrollLeft();

// 监听文档滚动的jquery方法
$(document).scroll(function(){
    console.log($(document).scrollTop());
    console.log($(document).scrollLeft());
});

 

5)innerHeight,匹配第一个匹配元素内部区域高度(包括补白、不包括边框)

$("#box").innerHeight()

 

6)innerWidth,匹配第一个匹配元素内部区域宽度(包括补白、不包括边框)

$("#box").innerWidth();

 

7)outerHeight,获取第一个匹配元素外部高度(默认包括补白和边框)

$("#box").outerHeight();

 

8)outerWeight,获取第一个匹配元素外部宽度(默认包括补白和边框)

$("#box").outerWidth();

 

9)width(),height()设置宽高

$("#box").width();

 

模仿淘宝导航栏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模仿淘宝导航栏</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        div{
            width: 100%;
        }
        div img{
            width: 100%;
        }
        .nav{
            display: none;
        }
    </style>
</head>
<body>
    <div class="top">
        <img src="top.jpg">
    </div>
    <div class="nav">
        <img src="nav.jpg">
    </div>
    <div class="taobao">
        <img src="taobao1.png">
    </div>
</body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function(){
            var h = $(".top").height();

            $(document).scroll(function(){
                var scrollTop = $(document).scrollTop();

                if (h < scrollTop){
                    $(".nav").css({display: "block", position: "fixed", top: 0})
                }else{
                    $(".nav").css({display: "none", position: "static", top: 0})
                }
            })
        })
    </script>
</html>

 

返回顶部的代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Return-Top</title>
    <style>
        .content{
            width:80%;
            margin:0 auto;
            height:800px;
            background-color:gray;
        }
        .returnTop{
            position:fixed;
            right:10px;
            bottom:20px;
            background-color:blue;
            width:40px;
            height:20px;
            font-size:10px;
            color:white;
        }
        .hide{
            display:none;
        }
    </style>
</head>
<body>
    <div class="content">Hello World</div>
    <div class="content">Hello World</div>
    <div class="content">Hello World</div>

    <div class="returnTop hide" onclick="ReturnTop();">返回顶部</div>

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

        function ReturnTop(){
            $(window).scrollTop(0);
        };
    </script>
</body>
</html>

 

3)尺寸

height([val]) 获取高度值

width([val]) 获取宽度值

 

菜单滑动代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rolling Menu</title>
    <style>
        body{
            margin:0;
            background-color:#dddddd;
        }
        .w{
            margin:0 auto;
            width:980px;
        }
        .pg-header{
            background-color: #555555;
            color:white;
            height:48px;
        }

        .pg-body .menu{
            width:180px;
            background-color:white;
            float:left;
        }

        .fixed{
            position:fixed;
            top:10px;
        }

        .pg-body .menu .active{
            background-color:#425a66;
            color:white;
        }
        .pg-body .content{
            position:absolute;
            background-color: whitesmoke;
            left:345px;
            right:200px;
            float:right;
        }
        .pg-body .content .item{
            height:900px;
        }
    </style>
</head>
<body>
    <div class="pg-header">
        <div class="w"></div>
    </div>

    <div class="pg-body">
        <div class="w">
            <div id="menu" class="menu">
                <ul>
                    <li i="1">第一部分</li>
                    <li i="2">第二部分</li>
                    <li i="3">第三部分</li>
                </ul>
            </div>
            <div id="content" class="content">
                <div class="item" t="1">法兰西</div>
                <div class="item" t="2">英吉利</div>
                <div class="item" t="3">美利坚</div>
            </div>
        </div>
    </div>

    <script src="jquery.js"></script>
    <script>
        // 监听窗体滑动事件
        window.onscroll=function(){
            var distance = $(window).scrollTop();
            // 如果滚轮滑动超过50,将左侧menu菜单固定住
            if(distance > 50){
                $(".menu").addClass("fixed");
            }else{
                $(".menu").removeClass("fixed");
            }

            if($(document).height() == $(window).height() + distance){
                $(".menu").children(":last").css("fontSize", "30px").siblings().css("fontSize", "15px");
                return
            }

            // 根据滑动的高度,左侧菜单动态变化
            $("#content").children().each(function(){
            var offset = $(this).offset().top;
            var total = $(this).height() + offset;
            if(distance > offset && distance < total){
                var index = $(this).attr("t");
                var new_index = "[i=" + index + "]";
                $(new_index).css("fontSize", "30px").siblings().css("fontSize","15px");

                return
            }
        });

        };

    </script>
</body>
</html>

 

关于each的return补充

// jquery的遍历方法 .each()
$("li").each(function(index, ele){
    var isDanger = $(this).hasClass("danger");
    
    if(isDanger){
        $(this).css("color", "red");
    }else{
        $(this).css("color", "green");
    }
}
 // 1. $.each return,跟外层函数无关
        // 2. $.each return false,表示each退出
        function f1(){
            var li = [1, 2, 3];
            $.each(li, function(k, v){
                console.log(k, v);
                if(k == 1){
                    return false;
                }
            });
            // end能够给在日志中输出
            console.log('end');
        }

 

选项卡案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>选项卡</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        ul{
            list-style: none;
        }
        /*清除浮动产生的问题*/
        #box:after{
            content: "";
            display: block;
            clear: both;
        }
        #box{
            width: 800px;
            border: 1px solid black;
            margin: 20px auto;
            background: blue;
        }
        #leftBox{
            width: 200px;
            float: left;
        }
        #leftBox li{
            width: 200px;
            height: 89px;
            background: red;
            margin-bottom: 2px;
            color: white;
            font: 50px/89px "宋体";
            text-align: center;
        }
        #rightBox div{
            width: 600px;
            float: left;
            display: none;
        }
        #rightBox p{
            width: 100%;
            height: 325px;
            font: 100px/325px "宋体";
            text-align: center;
            background: greenyellow;
        }
        /*父元素设置display: table使它成为一个块级表格元素*/
        /*子元素设置display: table-cell使子元素成为表格单元格,就好比是在表格中一样*/
        #rightBox ul{
            width: 600px;
            display: table;
        }
        #rightBox li{
            display: table-cell;
            background: purple;
            height: 40px;
            border-right: 2px solid blue;
            font: 30px/40px "宋体";
            text-align: center;
            color: white;
        }
        #leftBox .active{
            background: yellow;
            color: black;
        }
        #rightBox .active{
            background: white;
            color: black;
        }
    </style>
</head>
<body>
    <div class="box">
        <ul id="leftBox">
            <li>a</li>
            <li>b</li>
            <li>c</li>
            <li>d</li>
        </ul>
        <div id="rightBox">
            <div style="display: block">
                <p>a1</p>
                <ul>
                    <li class="active">a1</li>
                    <li>a2</li>
                    <li>a3</li>
                    <li>a4</li>
                </ul>
            </div>
            <div>
                <p>b1</p>
                <ul>
                    <li class="active">b1</li>
                    <li>b2</li>
                    <li>b3</li>
                    <li>b4</li>
                </ul>
            </div>
            <div>
                <p>c1</p>
                <ul>
                    <li class="active">c1</li>
                    <li>c2</li>
                    <li>c3</li>
                    <li>c4</li>
                </ul>
            </div>
            <div>
                <p>d1</p>
                <ul>
                    <li class="active">d1</li>
                    <li>d2</li>
                    <li>d3</li>
                    <li>d4</li>
                </ul>
            </div>
        </div>
    </div>
</body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function(){
            // 鼠标移入时触发事件
            $("#leftBox li").mouseover(function(){
                // 修改自己的样式
                $(this).addClass('active').siblings("li").removeClass("active");

                // 修改右边的div
                $("#rightBox div").eq($(this).index()).show().siblings("div").hide();
            })

            // 鼠标点击时触发事件
            $("#rightBox li").click(function(){
                $(this).addClass("active").siblings("li").removeClass("active");
                var liVal = $(this).html();
                $(this).parent().prev().html(liVal);
            })
        })
    </script>
</html>

 

小米官网效果1案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小米官网效果1</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        ul{list-style: none}
        .wrap{
            width: 980px;
            height: 612px;
            margin: 20px auto 0px;
            background: #f4f3f4;
            border: 1px solid gray;
        }
        ul li{
            float: left;
            margin-left: 10px;
            position: relative;
            overflow: hidden;
            width: 233px;
            height: 300px;
        }
        ul li p{
            width: 233px;
            height: 100px;
            line-height: 100px;
            position: absolute;
            background: rgba(245, 102, 51, .7);
            bottom: -100px;
            text-align: center;
            color: white;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <ul>
            <li><a href="#"><img src="xiaomi_01.png"/></a><p>百度一下,你就知道</p></li>
            <li><a href="#"><img src="xiaomi_02.png"/></a><p>百度一下,你就知道</p></li>

            <li><a href="#"><img src="xiaomi_03.png"/></a><p>百度一下,你就知道</p></li>
            <li><a href="#"><img src="xiaomi_04.png"/></a><p>百度一下,你就知道</p></li>
            <li><a href="#"><img src="xiaomi_05.png"/></a><p>百度一下,你就知道</p></li>
            <li><a href="#"><img src="xiaomi_07.png"/></a><p>百度一下,你就知道</p></li>
            <li><a href="#"><img src="xiaomi_08.png"/></a><p>百度一下,你就知道</p></li>
            <li><a href="#"><img src="xiaomi_09.png"/></a><p>百度一下,你就知道</p></span></li>
        </ul>
    </div>
</body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // mouseenter与mouseleave效果
        $(function(){
            $(".wrap ul li").hover(function(){
                $(this).children("p").animate({bottom:0}, 100)
            }, function(){
                $(this).children("p").animate({bottom:-100}, 100)
            })
        })
    </script>
</html>

 

动态实现轮播图案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动态实现轮播图</title>
    <style type="text/css">
        *{padding:0; margin: 0;}
        ul{list-style: none}

        #box{
            width: 240px;
            height: 180px;
            position: relative;
            margin: 50px auto;
            overflow: hidden;
        }
        ul{
            width: 960px;
            position: absolute;
        }
        ul li{
            float: left;
        }
        p{
            position: absolute;
            left: 80px;
            bottom: 30px;
        }
        p span{
            color: red;
            display: inline-block;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            cursor: pointer;
        }
        p span.active{
            color: white;
            background: greenyellow;
        }
    </style>
</head>
<body>
    <div id="box">
        <ul>

        </ul>
        <p></p>
    </div>
    <button id="play">播放</button>
    <button id="stop">停止</button>
</body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // 1.获取本地图片数据
        var imgsAddr = ["01.jpg", "02.jpg", "03.jpg", "04.jpg"];

        // 2.动态生成图片
        for(var i = 0; i < imgsAddr.length; i++){
            $("ul").append("<li><img src=" + imgsAddr[i] + "></li>");
        }

        // 生成索引
        var str = "";
        $("li").each(function(i, ele){
            str += "<span>" + (i+1) + "</span>";
        })
        $("p").html(str);

        // 默认设置索引的第一个为active
        $("span:first").addClass("active");
        var index = 0;

        // 5.点击索引
        $("span").click(function(){
            $(this).addClass("active").siblings("span").removeClass("active");

            // 获取我当前点击的索引
            index = $(this).index();

            $("ul").animate(
                {left: -240 * index + "px"}, 100)
        })

        // 6.开启定时器,索引跟着走,图片跟着走
        var timer = null;
        $("#play").click(function(){
            timer = setInterval(next, 1000);

            function next(){
                if(index == $("li").length - 1){
                    index = 0;
                    $("p span").first().addClass("active").siblings("span").removeClass("active");
                    $("ul").css("left", 0);
                }else{
                    index++;
                    $("p span").eq(index).addClass("active").siblings("span").removeClass("active");
                    $("ul").css("left", -240 * index);
                }
            }

            $("#stop").click(function(){
                clearInterval(timer);
            })
        })

    </script>
</html>

 

 

 

8. 事件

加载DOM:.ready(),将函数绑定到文档的就绪事件(当文档完成加载时)

$(document).ready(function(){}) --------> $(function(){}) 先等待文档流加载完,再执行jQuery代码

1)事件流:描述的是从页面中接收事件的顺序

“DOM2级事件”规定的事件流包括三个阶段:

  • 事件捕获阶段
  • 处于目标阶段
  • 事件冒泡阶段

 

2)jQuery的事件对象和事件冒泡

事件对象的常见属性

e.type,获取事件的类型

e.target,获取事件发生的DOM对象

e.pageX和e.pageY,获取到光标相对于页面的x的坐标和y的坐标

e.which,该方法的作用是在鼠标单击事件中获取到鼠标的左、中、右键;在键盘事件中获取键盘的按键

<script type="text/javascript">
    // 入口函数时间
    $(function(){
        // 事件对象
        $(".p1").hover(function(e){
            // 事件类型 事件属性
            console.log(e.type);
            console.log(e.target);

            console.log(e.pageX);
            console.log(e.pageY);

            alert("当前按钮事件触发了");

            // 常用的事件 方法 1. 阻止事件冒泡;2.阻止默认事件
            // 1. 阻止事件冒泡
            e.stopPropagation();
            
        })

        $("#box").click(function(){
            alert("#box盒子事件触发了");
        })

        $("a").click(function(e){
            // 阻止a标签的默认事件,即跳转
            e.preventDefault();
            alert("a标签事件")
        })

    }
</script>

 

3)事件绑定

<script type="text/javascript">
    $(function(){
        // 给当前的dom元素绑定事件
        // 语法:jquery对象.bind("事件类型", fn)
        $("#box").bind("click mouseenter", function(){
            alert("事件被绑定了");
        })

        function add(){
            console.log("click");
        }
        function add2(){
            console.log("mouseover");
        }
        $("#box").bind({
            "click": add,
            "mouseover": add2
        })

        // 事件移除,如果没有参数,表示移除所有事件
        setTimeout(function(){
            $("#box").unbind();
            $("#box").unbind("click", function(){
                console.log(123);
            })
        }, 3000)
    }
</script>

 

4)自定义事件和事件代理

<script type="text/javascript">
    $(function(){
        // 绑定自定义事件
        $("button").bind("myClick", function(e, a, b, c){
            alert("自定义事件");
            alert(a);
            alert(b);
            alert(c);
        })

        // 触发自定义事件
        $("button").trigger("myClick", [1,2,3]);
            console.log("触发自定义事件");

        // 事件处理 自己完成不了当前的点击事件,交给父级元素来处理该事件
        // 父级.on("事件名字", "点击当前的标签元素", fn)
        $("ul").on("click", "li", function(){
            console.log(this);
        })
    }
</script>


$("ul").delegate("li", "click", function(){}) 什么时候使用再绑定

 

5)鼠标事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			*{padding: 0;margin: 0;}
			#box{
				width: 200px;
				height: 200px;
				background: gray;
			}
			
			#child{
				width: 100px;
				height: 100px;
				background: yellow;
			}
		</style>
	</head>
	<body>
		
		<div id="box">
			<div id="child">
				
			</div>
		</div>
	</body>
	<script src="jquery-3.2.1.js"></script>
	<script type="text/javascript">
		
		$(document).ready(function(){
			//点击事件click,鼠标单击触发事件,参数可选(data, fn)
			$("#box").click(function(){
				console.log('click')
			})
			
			//双击事件dbclick,双击触发
			$("#box").dbclick(function(){
				console.log('dbclick')
			})

			//鼠标按下不松开触发事件
			$("#box").mousedown(function(){
				console.log('mousedown');
			})
				
			//鼠标松开触发事件
			$("#box").mouseup(function(){
				console.log('mouseup');
			})
			
			// 鼠标移入和移出触发事件,鼠标指针穿过/离开被选元素或者当前元素的子元素,会触发事件
			$('#box').mouseover(function(){
				console.log('mouseover');
			})
			$('#box').mouseout(function(){
				console.log('mouseout');
			})

			// 鼠标进入和离开触发事件,鼠标指针只在穿过/离开被选元素触发事件
			$('#box').mouseenter(function(){
				console.log('mouseenter');
			})
			$('#box').mouseleave(function(){
				console.log('mouseleave');
			})
            
            // 鼠标移动事件
			$("#box").mousemove(function(){
				console.log('mousemove');
			})

            // 鼠标聚焦/失去焦点触发事件(不支持冒泡)
            $("#inputBox").focus(function(){
                console.log('focus');
            })
            $("#inputBox").blur(function(){
                console.log('blur');
            })

            // 键盘按键按下/弹起触发
            $("input[type=password]").keydown(function(){
                console.log($(this).val());
            })
            $("input[type=password]").keyup(function(){
                console.log($(this).val());
            })
		})
	</script>
</html>

 

6)表单事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单事件</title>
    <style type="text/css">
        .show{
            color: red;
        }
    </style>
</head>
<body>
    <form action="http://www.baidu">
        <select name="sweets" id="sweets" multiple="">
            <option value="">巧克力</option>
            <option value="">糖果</option>
            <option value="">焦糖</option>
            <option value="">曲奇饼</option>
            <option value="">烧饼</option>
            <option value="">麦香饼</option>
        </select>

        <input type="text" value="hello" id="target">
        <input type="submit" value="sumit">
        <input type="button" name="" id="" value="按钮">
    </form>

    <input id="other" type="text" value="Trigger the handler">

    <div class="show"></div>

</body>
    <script src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // 1.change()事件,此事件仅限于input元素,textarea select
        $("select").change(function(){
            console.log($("select option:selected").text());
            $(".show").text($("select option:selected").text());
        })

        // 2.select(),仅限于用在input type=text textarea
        $("#other").select(function(){
            console.log($(this).val());
        })

        // 3.submit
        $("form").submit(function(e){
            // 阻止默认事件
            e.preventDefault();
        })
    </script>
</html>

 

 

事件代码案例:

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

    </style>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <button>添加</button>

    <script src="jquery.js"></script>
    <script>
        $(function(){
            // 这样绑定的事件在页面载入完成后就无法给新添加的标签绑定事件
            $("li").click(function(){
                alert("666");
            });

            // 将某标签下的标签进行委托管理可解决上述问题
            // 批量处理最好选用delegate方式
            $("ul").delegate("li", "click", function(){
                alert("666");
            });

            $("button").click(function(){
               $("ul").append("<li>N</li>")
            });
        });
    </script>
</body>
</html>

 

 

 

9. jQuery Ajax

Ajax = 异步的javascript和XML(Asynchronous Javascript and XML)

简言之,在不重载整个网页的情况下,Ajax通过后台加载数据,并在网页上进行显示。

通过jQuery Ajax方法,能够使用HTTP Get和HTTP Post从远程服务器上请求文本、HTML、XML或JSON - 同时能够把这些外部数据直接载入网页的被选元素中。

 

1)jQuery的load()方法

jQuery load()方法是简单但强大的Ajax方法。

load()方法从服务器加载数据,并把返回的数据放入被选元素中。

语法:$("selector").load(url, data, callback);

url为必要参数,规定记载的url地址

data为可选参数,规定与请求一同发送的查询字符串键值对的集合

callback为可选参数,规定load()方法完成后执行的函数名称

$("btn").click(function(){
    // 只传了一个url,表示在id为#new-projects的元素里加载index.html
    $("#new-projects").load("./index.html");
})

$("btn").click(function(){
    // 只传一个url,导入的index.html文件含有多个传递函数,类似于:index/html?name='张三'
    $("#new-projects").load("./index.html", {"name": "adam", "age": 22});
})

$("btn").click(function(){
    // 加载文件之后,会有个回调函数,表示加载成功的函数
    $("#new-projects").load("./index.html", {"name": "bruce", "age": 20}, function(){
        alert("回调函数");
    });
})

 

2)jquery的getJSON方法

jQuery的Ajax中使用getJSON()方法异步加载JSON格式数据。

语法:$.getJSON(url, [data], [callback])

url参数为请求加载json格式文件的服务器地址

data可选参数为请求时发送的数据

callback为数据请求后调用的回调函数

$getJSON("./data/getJSON.json", function(data){
    var str = "";
    $.each(data, function(index, ele){
        $("ul").append("<li>" + ele.name + "</li>");
    });
})

 

3)jquery的$.get()方法

$.get()方法通过HTTP GET请求从服务器上请求数据

语法:$.get(URL, callback);

url是必需参数,规定请求的路径

callback参数为数据请求成功后执行的函数

$.get("./data/getJSON.json", function(data, status){
    console.log(status);
})

 

4)jqeury的$.post()方法

于get()方法相比,post()方法多用于以POST方式向服务器发送数据,并将处理结果返回页面

语法:$.post(URL, data, callback);

url为必需函数,规定请求的路径

data参数是连同请求发送的数据

callback参数为数据请求成功后执行的函数

$.post("/index", {"name": "adam"}, function(data, status){
    console.log(status);
})

 

5)jquery的$.ajax()方法

jquery的$.ajax()方法是做ajax技术经常使用的一个方法。

参数如下:

1. url:要求为String类型的参数,(默认当前页面地址)

2. type:要求为String类型的参数,请求方式(post或get)默认为get

3. timeout:要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。

4. async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。

5. cache:要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false),设置为false将不会从浏览器缓存中加载请求信息。

6. data:要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get请求中将附加在url后。防止这种自动转换,可以查看processData选项。对象必须为key/value格式,例如{"name": "adam"}转换为&name=adam。如果是数组,jQuery将自动为不同值对应同一个名称。例如{foo:["bar1", "bar2"]}转换为&foo=bar1&foo=bar2

7. dataType:要求为String类型的参数,预期服务器返回的数据类型。如果不指定,jQuery将自动根据http包mime信息返回repsonseXML或responseText,并作为回调函数参数传递。可用的类型如下:xml:返回XML文档,可用jQuery处理。html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都转为get请求。json:返回JSON数据。jsonp:JSONP格式。使用JSONP形式调用函数时,例如myurl?callback=?,jQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。text:返回纯文本字符串

$(document).ready(function(){
    // get请求
    $.ajax({
        url: "./index.html",
        type: "get",
        dataType: "json",
        success: function(data){
            console.log(data);
        },
        error: function(){
            
        }    
    })


    // post请求
    $.ajax({
        url: "./index.html",
        type: "post",
        data: {
            username: "adam",
            password: "123",
        },
        success: function(data){
            if(data.state == 'ok' && data.status == "200"){
                console.log("登陆成功");
            }
        },
        error: function(err){
            console.log(err);
        }
    })
})

 

 

 

11. jQuery扩展

jQuery.extend(object) 在jQuery命名空间上增加两个函数

jQuery.extend({
            min:function(a,b){return a < b ? a : b},
            max:function(a,b){return a > b ? a : b}
        });
        
        jQuery.min(10, 20) // 结果为10
        jQuery.max(10, 20) // 结果为20


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

 

增加两个插件方法的代码案例:

 

jQuery.fn.extend({
            check:function(){
                return this.each(function(){this.checked = true; });
            },
            uncheck:function(){
                return this.each(function(){this.checked = false; });
            }
        });
        
        $("input[type='checkbox']").check();
        $("input[type='checkbox']").uncheck();

 

 

 

12. 动画效果

1)隐藏与显示代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hide and Show</title>
    <style>

    </style>
</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(500);
            });

        });

    </script>
</body>
</html>


2)淡入与淡出代码案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fade In and Fade Out</title>
    <style>

    </style>
</head>
<body>
    <div id="1" style="display:none;width:80px;height:80px;background-color: blue"></div>
    <div id="2" style="display:none;width:80px;height:80px;background-color: red"></div>
    <div id="3" style="display:none;width:80px;height:80px;background-color: green"></div>

    <button id="in">fadein</button>
    <button id="out">fadeout</button>
    <button id="toggle">fadetoggle</button>
    <button id="fadeto">fadeto</button>

    <script src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function(){
            $("#in").click(function(){
                $("#1").fadeIn(1000);
                $("#2").fadeIn(1000);
                $("#3").fadeIn(1000);
            });
            $("#out").click(function(){
                $("#1").fadeOut(1000);
                $("#2").fadeOut(1000);
                $("#3").fadeOut(1000);
            });
            $("#toggle").click(function(){
                $("#1").toggle(1000);
                $("#2").toggle(1000);
                $("#3").toggle(1000);
            });
            $("#fadeto").click(function(){
                $("#1").fadeTo(1000, 0.4);
                $("#2").fadeTo(1000, 0.5);
                $("#3").fadeTo(1000, 0);
            });
        });

    </script>
</body>
</html>

 

3)下滑/隐藏代码案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Slide Down And Slide Up</title>
    <style>
        div{
            background-color:black;
            color:white;
            padding:5px;
            border:solid 1px grey;
        }
        #content{
            padding:50px;
            display:none;
        }
    </style>
</head>
<body>
    <div id="flipshow">出现</div>
    <div id="fliphide">隐藏</div>
    <div id="toggle">Toggle</div>
    <div id="content">Hello World</div>


    <script src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function(){
            $("#flipshow").click(function(){
                $("#content").slideDown(1000);
            });

            $("#fliphide").click(function(){
                $("#content").slideUp(1000);
            });

            $("#toggle").click(function(){
                $("#content").slideToggle(1000);
            });
        });

    </script>
</body>
</html>


4)轮播图代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rolling Panel</title>
    <style rel="stylesheet">
        *{
            margin:0;
            padding:0;
        }
        ul li{
            list-style: none;
        }
        .outer{
            height:625px;
            width:1024px;
            border:dashed blue 5px;
            margin:0 auto;
            position:relative;
        }
        .outer .img li{
            position:absolute;
            left:0;
            top:0;
        }
        .outer .num{
            position:absolute;
            left:0;
            bottom:10px;
            text-align:center;
            width:100%;
            font-size:0px;
        }
        .outer .num li{
            height:20px;
            width:20px;
            background-color:gray;
            border-radius: 60%;
            font-size:16px;
            color:white;
            text-align:center;
            line-height: 20px;
            display:inline-block;
            margin:5px;
            cursor:pointer;
        }
        .button{
            height:60px;
            width:24px;
            background-color:darkgray;
            position:absolute;
            /*left:0px;*/
            top:50%;
            margin-top:-30px;
            opacity: .4;
            font-size:25px;
            font-weight:bolder;
            text-align: center;
            line-height:60px;
            color:white;
            display:none;
        }
        .btn-right{
            right:0;
        }
        .outer:hover .button{
            display:block;
        }
        .outer .num li.current{
            background-color:red;
        }
    </style>
</head>
<body>
    <div class="outer">
        <ul class="img">
            <li><img src="picture/2.jpg"></li>
            <li><img src="picture/3.jpg"></li>
            <li><img src="picture/4.jpg"></li>
        </ul>


        <ul class="num">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>

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


    <script src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function() {
            $(".num li").first().addClass("current");
            // 手动控制轮播
            $(".num li").mouseover(function(){
                $(this).addClass("current").siblings().removeClass("current");
                var index = $(this).index();
                i = index;
                $(".img li").eq(index).fadeIn(1000).siblings().fadeOut(1000);
            });

            // 自动轮播
            i = 0;
            var time = setInterval(move, 1500);
            function move(){
                i++;
                if(i == 3){
                    i = 0;
                }
                $(".num li").eq(i).addClass("current").siblings().removeClass("current");
                $(".img li").eq(i).fadeIn(1000).siblings().fadeOut(1000);

            }

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

            $(".btn-right").click(function(){
                move();
            });
            $(".btn-left").click(function(){
                if(i == 0){
                    i = 3;
                }
                i = i - 2;
                move();
            });
        });




    </script>
</body>
</html>


5)拖动面板代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Moving Panel</title>
    <style rel="stylesheet">

    </style>
</head>
<body>
    <div style="border:1px solid #ddd;width:600px;position:absolute">
        <div id="title" style="background-color: black;height:40px;color:white;">
            标题
        </div>
        <div style="height:300px;">
            内容
        </div>
    </div>

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

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

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

                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);

                $(this).parent().css('left', x + 'px');
                $(this).parent().css('top', y + 'px');
            }).mouseup(function(){
                $(this).unbind('mousemove');
            });
            
        });
    </script>
</body>
</html>

 

6)模态对话框代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Model Input Window</title>
    <style rel="stylesheet">
        .shadow{
            position:fixed;
            left:0;
            top:0;
            right:0;
            bottom:0;
            background:rgba(0,0,0,0.4);
            z-index:5;
        }
        .model{
            position:fixed;
            left:50%;
            top:50%;
            width:400px;
            height:300px;
            margin-top:-150px;
            margin-left:-200px;
            z-index:10;
            border:1px solid #ddd;
            background-color:slategrey;
        }
        .hide{
            display:none
        }

    </style>
</head>
<body>
    <button onclick="Add();">添加</button>
    <table border="1px;">
        <thead>
            <tr>
                <th>主机名</th>
                <th>IP</th>
                <th>端口</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td target="host">t1</td>
                <td target="ip">1.1.1.1</td>
                <td target="port">80</td>
                <td onclick="Edit(this);">Edit</td>
            </tr>
            <tr>
                <td>t2</td>
                <td>1.1.1.1</td>
                <td>8888</td>
                <td>Edit</td>
            </tr>
            <tr>
                <td>t3</td>
                <td>1.1.1.1</td>
                <td>9999</td>
                <td>Edit</td>
            </tr>
        </tbody>
    </table>

    <div class="shadow hide"></div>
    <div class="model hide">
        <form action="" method="get">
            <p><input type="text" id="host" name="host"></p>
            <p><input type="text" id="ip" name="ip"></p>
            <p><input type="text" id="port" name="port"></p>
            <input type="submit" value="提交" onclick="return SubmitForm();">
            <input type="button" value="取消" onclick="Hide();">
        </form>
    </div>

    <script src="jquery-3.2.1.js"></script>
    <script>
        function SubmitForm(){
            var flag = true;
            $(".model").find("input[type='text']").each(function(){
                var value = $(this).val();
                if(value.trim().length == 0){
                    flag = false;
                }
            });
            return flag;
        }
        
        function Edit(arg){
            $(".shadow, .model").removeClass("hide");

            var prevList = $(arg).prevAll();
            prevList.each(function(k, v){
                var text = $(this).text();
                var target = $(this).attr("target");
                $("#" + target).val(text);
            });
        }
        function Hide(){
            $(".shadow, .model").addClass("hide");
            $(".model").find("input[type='text']").val("");
        }
        function Add(){
            $(".shadow, .model").removeClass("hide");
        }
    </script>
</body>
</html>

 

7)clone方法应用的代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Clone</title>
    <style rel="stylesheet">
        .outer .section ul li{
            display:inline-block;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="section">
            <ul>
                <li><div class="icons"><button onclick="Add(this);">+</button></div></li>
                <li><div class="inputs"><input type="checkbox"></div></li>
                <li><div class="inputs"><input type="text" value="IP"></div></li>
            </ul>
        </div>
    </div>

    <script src="jquery-3.2.1.js"></script>
    <script>
        function Add(arg){
            // 找到class = "section"的父级标签进行克隆
            var item = $(arg).parent().parent().parent().parent().clone();
            $(".outer").append(item);

            item.find("button").text("-");
            item.find("button").attr("onclick","Remove(this);");
        }

        function Remove(arg){
            $(arg).parent().parent().parent().parent().remove();
        }
    </script>
</body>
</html>

 

8)编辑框代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Editing Panel</title>
    <style rel="stylesheet">

    </style>
</head>
<body>
    <div>
        <button onclick="CheckAll('#edit_mode', '#tb1')">全选</button>
        <button onclick="CheckReverse('#edit_mode', '#tb1')">反选</button>
        <button onclick="CheckCancel('#edit_mode', '#tb1')">取消</button>
        <button id="edit_mode" class="edit-mode" onclick="EditMode(this,'#tb1');">进入编辑模式</button>
    </div>

    <table border="1px;">
        <thead>
            <tr>
                <th>选择</th>
                <th>主机名</th>
                <th>端口</th>
                <th>状态</th>
            </tr>
        </thead>
        <tbody id="tb1">
            <tr>
                <td><input type="checkbox"></td>
                <td edit="true">t1</td>
                <td edit="true">t11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td edit="true">t2</td>
                <td edit="true">t22</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td edit="true">t3</td>
                <td edit="true">t33</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">下线</td>
            </tr>

        </tbody>
    </table>

    <script src="jquery-3.2.1.js"></script>
    <script type="text/javascript">
        STATUS = [
            {"id":1, "value": "在线"},
            {"id":2, "value": "下线"}
        ];

        // 监听是否已经按下ctrl键
        window.globalCtrlKeyPress = false;
        window.onkeydown = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = true;
            }
        };
        window.onkeyup = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = false;
            }
        };
        
        // 按下ctrl,联动表格中正在编辑的select
        function MultiSelect(ths){
            if(window.globalCtrlKeyPress){
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                    $(this).parent().parent().children().eq(index).children().val(value);
                });
            }
        }

        $(function(){
            BindSingleCheck("#edit_mode", "#tb1");
        });

        function BindSingleCheck(mode, tb){
            $(tb).find(":checkbox").bind("click", function(){
                var tr = $(this).parent().parent();
                // 是否进入编辑模式
                if($(mode).hasClass("editing")){
                    // 是否已经选中
                    // 如果没有选中,进入编辑模式
                    // 如果已经选中,退出编辑模式
                    // checkbox默认事件优先于自定义事件
                    if($(this).prop('checked')){
                        RowIntoEdit(tr);
                    }else{
                        RowOutEdit(tr);
                    }
                }
            });
        }

        function CreateSelect(attrs, csses, option_dict, item_key, item_value, current_val){
            var sel = document.createElement("select");
            // {"k1":"v1", "k2":"v2"}
            // 在sel中设置属性<select k1='v1' k2='v2'>
            $.each(attrs, function(k, v){
                $(sel).attr(k, v);
            });
            // csses:{'fontSize':18px; color:red;}
            // sel中设置样式<select style="font-size:18px; color:red">
            $.each(csses, function(k,v){
                $(sel).css(k, v);
            });
            $.each(option_dict, function(k,v){
                var opt1 = document.createElement("option");
                var sel_text = v[item_value];
                var sel_value = v[item_key];
                
                if(sel_value == current_val){
                    $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected', true).appendTo($(sel));
                }else{
                    $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
                }
             });
        }

        function RowIntoEdit(tr){
            tr.children().each(function(){
                if($(this).attr("edit") == "true"){
                    if($(this).attr("edit-type") == "select"){
                        var select_val = $(this).attr("sel-val");
                        var global_key = $(this).attr("global-key");
                        // "STATUS" window[global_key]
                        // 生成select标签,并且将其设置默认值select_val
                        var select_tag = CreateSelect({"onchange":"MultiSelect(this);",});
                        $(this).html(select_tag);
                    }else{
                        var origin_value = $(this).text();
                        var temp = "<input value='" + origin_value + "'/>";
                        $(this).html(temp);
                    }
                }
            });
        }

        function RowOutEdit(tr){
            tr.children().each(function(){
                if($(this).attr("edit") == "true"){
                    if($(this).attr("edit-type") == "select"){
                        var new_val = $(this).children(":first").val();
                        var new_text = $(this).children(":first").find("option[value='" + new_val + "']").text();
                        $(this).attr("sel-val", new_val);
                        $(this).text(new_text);
                    }else{
                        var origin_value = $(this).children().first().val();
                        $(this).text(origin_value);
                    }
                }
            });
        }

        function CheckAll(mode, tb){
            // mode = #edit_mode => 用于检测用户是否点击进入编辑模式
            // tb = #tb1 => table中的tbody
            if($(mode).hasClass("editing")){

                $(tb).children().each(function(){
                    // tr为循环的当前行
                    var tr = $(this);
                    var checkbox = tr.children().first().find(":checkbox");

                    if(checkbox.prop("checked")){

                    }else{
                        checkbox.prop("checked", true);
                        // 进入编辑模式
                        RowIntoEdit(tr);
                    }
                });
            }else{
                $(tb).find(":checkbox").prop("checked", true);
            }
        }

        function CheckReverse(mode, tb){
            if($(mode).hasClass("editing")){
                $(tb).children().each(function(){
                    var tr = $(this);
                    var check_box = tr.children().first().find(":checkbox");
                    if(check_box.prop("checked")){
                       check_box.prop("checked", false);
                       RowOutEdit(tr);
                    }else{
                       check_box.prop("checked", true);
                       RowIntoEdit(tr);
                    }
                });
            }else{
                $(tb).children().each(function(){
                   var tr = $(this);
                   var check_box = tr.children().first().find(":checkbox");
                   if(check_box.prop("checked")){
                       check_box.prop("checked", false);
                   }else{
                       check_box.prop("checked", true);
                   }
                });
            }
        }

        function CheckCancel(mode, tb){
            if($(mode).hasClass("editing")){
                $(tb).children().each(function(){
                    var tr = $(this);
                    var check_box = tr.children().first().find(":checkbox");

                    if(check_box.prop("checked")){
                        check_box.prop("checked", false);
                        // 当前行退出编辑模式
                        RowOutEdit(tr);
                    }else{

                    }
                });
            }else{
                $(tb).find(":checkbox").prop("checked", false);
            }
        }

        function EditMode(ths, tb){
            if($(ths).hasClass("editing")){
                $(ths).removeClass("editing");
                $(tb).children().each(function(){
                   var tr = $(this);
                   var check_box = tr.children().first().find(":checkbox");
                   if(check_box.prop("checked")){
                       RowOutEdit(tr);
                   }else {

                   }
                });
            }else{
                $(ths).addClass("editing");
                $(tb).children().each(function(){
                    var tr = $(this);
                    var check_box = tr.children().first().find(":checkbox");
                    if(check_box.prop("checked")){
                        RowIntoEdit(tr);
                    }else{

                    }
                });
            }
        }


    </script>
</body>
</html>

 

9)jQuery放大镜代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Scale up</title>
    <style rel="stylesheet">
        *{
            margin:0;
            padding:0;
        }
        .outer{
            width:240px;
            height:157px;
            border: 2px dashed lightgray;
        }
        .outer .small-box{
            position:relative;
        }
        .outer .small-box .float{
            width:120px;
            height:78px;
            background-color:grey;
            opacity:0.4;
            position:absolute;
        }
        .outer .big-box{
            position:absolute;
            left:250px;
            top:0;
            width:400px;
            height:200px;
            overflow:hidden;
            border:1px solid lightcyan;
        }
        .outer .big-box img{
            position:absolute;
            z-index:10;
        }
        .hide{
            display:none;
        }

    </style>
</head>
<body>
    <div class="outer">
        <div class="small-box">
            <div class="float hide"></div>
            <img src="picture/small.jpg">
        </div>
        <div class="big-box hide">
            <img src="picture/big.jpg">
        </div>
    </div>

    <script src="jquery-3.2.1.js"></script>
    <script type="text/javascript">
        $(".small-box").mouseover(function(){
            $(".float").removeClass("hide");
            $(".big-box").removeClass("hide");
        });

        $(".small-box").mouseout(function(){
            $(".float").addClass("hide");
            $(".big-box").addClass("hide");
        });

        $(".small-box").mousemove(function(e){
            var _event = e || window.event;

            var small_box_height = $(".small-box").height();
            var small_box_width = $(".small-box").width();

            var float_panel_height = $(".float").height();
            var float_panel_width = $(".float").width();

            var float_panel_height_half = $(".float").height() / 2;
            var float_panel_width_half = $(".float").width() / 2;

            mouse_left = _event.clientX - float_panel_width_half;
            mouse_top = _event.clientY - float_panel_height_half;

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

            if(mouse_top < 0){
                mouse_top = 0;
            }else if(mouse_top > small_box_height - float_panel_height){
                mouse_top = small_box_height - float_panel_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_panel_width);
            var percentY = ($(".big-box img").height() - $(".big-box").height()) / (small_box_height - float_panel_height);

            // 大图片上的移动
            $(".big-box img").css("left", -percentX * mouse_left + "px");
            $(".big-box img").css("top", -percentY * mouse_top + "px");

        });
    </script>
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

本文标签: 属性操作位置效果事件