jQuery基础与实例

一、简介


 

1、什么是jQuery

  jQuery是一个轻量级、快速简洁的javaScript库,能让我们方便快捷的选择元素操作元素属性。

2、下载地址

3、jQuery使用方式

  $("div")等价于jQuery("div"),通常使用前者。

 

二、查找元素


 

1、选择器

  a、基本选择器

<!--基本选择器-->
    $("#id")            //ID选择器
    $("div")            //元素选择器
    $(".classname")     //类选择器
    $(".classname,.classname1,#id1")     //组合选择器


<!--层级选择器-->

    $("#id>.classname ")    //子元素选择器
    $("#id .classname ")    //后代元素选择器
    $("#id + .classname ")    //紧邻下一个元素选择器
    $("#id ~ .classname ")    //兄弟元素选择器

<!--属性选择器--> $("div[id]") //所有含有 id 属性的 div 元素 $("div[id='123']") // id属性值为123的div 元素 $("div[id='!123']") // id属性值不等于123的div 元素 $("div[id='^qq']") // id属性值以qq开头的div 元素 $("div[id='$zz']") // id属性值以zz结尾的div 元素 $("div[id='*bb']") // id属性值包含bb的div 元素 $("input[id][name$='man']") //多属性选过滤,同时满足两个属性的条件的元素


  b、表单选择器

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

<!--表单对象属性-->
$("input:enable")       //可用input元素
$("input:disable")       //禁用的input元素
$("input:checked")    //所有选中的元素
$("select option:selected")    //select中所有选中的option元素

 

2、筛选器

  a、基本筛选器

<!--基本筛选器-->
$('li:first')    //第一个元素
$('li:last')     //最后一个元素

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

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

  b、内容筛选器


$("div:contains('John')") //包含John文本的元素 $("td:empty") //不包含子元素或者文本的空元素 $("div:has(selector)") //含有选择器所匹配的元素 $("td:parent") //含有子元素或者文本的元素

   c、可见性筛选器

$("tr:hidden")      //所有隐藏的tr元素
$("tr:visible")     //所有可见的tr元素

 

3、过滤器

过滤器行为基本和筛选器一致,但过滤器作为方法来调用,使用更加灵活,因此尽可能使用过滤器而不是筛选器。

  a、过滤

$("p").eq(0)       //当前操作中第N个jQuery对象,类似索引
$('li').first()    //第一个元素
$('li').last()     //最后一个元素
$(this).hasClass("test")    //元素是否含有某个特定的类,返回布尔值
$('li').has('ul')  //包含特定后代的元素
$('li').slice(0,2)  //选取一个子集,如果起始是负数,则从后开始。
$("input[type='checkbox']").parent().is("form") //如果其中至少有一个元素符合这个给定的表达式就返回true。

 

  b、查找

<!--查找-->
//查找方法中都可以带表达式进行过滤
$("div").children() //div中的每个子元素,第一层 $("div").find("span") //div中的包含的所有span元素,后代
$("div").contents()    //div下的所有节点,包括文本节点而不是元素。页面有Iframe需要载入的时候用到contents()
$("div").filter("span")   //包含span元素的div标签。 $("p").next()    //紧邻p元素后的一个同辈元素 $("p").nextAll() //p元素之后所有的同辈元素 $("#test").nextUntil("#test2") //id为"#test"元素之后到id为'#test2'之间所有的同辈元素,掐头去尾 $("p").prev() //紧邻p元素前的一个同辈元素 $("p").prevAll() //p元素之前所有的同辈元素 $("#test").prevUntil("#test2") //id为"#test"元素之前到id为'#test2'之间所有的同辈元素,掐头去尾 $("p").parent() //每个p元素的父元素 $("p").parents() //每个p元素的所有祖先元素,body,html $("#test").parentsUntil("#test2") //id为"#test"元素到id为'#test2'之间所有的父级元素,掐头去尾 $("div").siblings() //所有的同辈元素,不包括自己

 $("p").find("span").end()  //结束当前链条中的最近的筛选操作,并将匹配筛选之前的元素。

 

 $("li").index("#test")  //id为test的li元素,在选择器中的的相对位置索引。如果index()不传参数,则结果为li元素的第一个元素相对于同辈元素的索引位置。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
    a {
        font-size: 30px;
        font-weight: 900;
    }
    </style>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <h2>index方法</h2>
    <ul>
        <a></a>
        <a></a>
        <li id="test1">1</li>
        <li id="test2">2</li>
        <li id="test3">3</li>
    </ul>
    <ul>
        <li id="test4">4</li>
        <li id="test5">5</li>
        <li id="test6">6</li>
    </ul>
    <select id="animation">
        <option value="1">index无参数</option>
        <option value="2">index传递dom</option>
        <option value="3">index传递jQuery对象</option>
    </select>
    <input id="exec" type="button" value="点击执行">
    <br />
    <br /> 索引结果:
    <span></span>
    <script type="text/javascript">
    $("#exec").click(function() {
        var v = $("#animation").val();

        var $span = $("span");
        $span.empty();

        if (v == "1") {
            //找到第一个li的同辈节点中的索引位置
            $span.text($("li").index())
        } else if (v == "2") {

            //通过传递dom查找
            $span.text($("li").index(document.getElementById("test5")))

        } else if (v == "3") {
            //通过传递jQuery对象查找
            $span.text($("li").index($("#test6")))

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

</html>
index样例

 

三、操作元素


 

1、属性操作

  a、基本属性操作

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

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

//需要注意的是:当我们对checkbox,radio,select等选择性的表当取选中状态的时候,不要使用checked属性,而使用prop属性。

 

 

  b、CSS类操作

$("p").addClass("selected");      //为p元素加上 'selected' 类
$("p").removeClass("selected");    //从p元素中删除 'selected' 类
$("p").toggleClass("selected");    //如果存在就删除,否则就添加
$("p").hasClass("active");      //判断p元素是否存在active的类,返回bool值

 

  c、HTML代码/文本/值

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

 

 

 2、CSS操作

  a、CSS样式操作

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

 

  b、位置

$('p').offset()     //元素的border外边界相对页面文档(document)左上角的偏移,Object {top: 16, left: 16}
$('p').offset().top
$('p').offset().left
$("p").position()   //元素的margin外边界相对于有postion属性的父元素的padding内边界距离,对可见元素有效,Object {top: 2, left: 2},如果父元素没有设置postion属性会一直向外查找直到body元素,这时就和offset的值相同。

$(window).scrollTop()    //获取滚轮滑的高度
$(window).scrollLeft()   //获取滚轮滑的宽度
$(window).scrollTop('100')    //设置滚轮滑的高度为100
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            padding:0;
            margin:0;
        }
        .d1 {
            height: 100px;
            width:100px;
            border: 1px solid blue;
            padding: 2px;
            margin: 4px;;
            background-color: #cccccc;
            position: relative;
        }
        .d2{
            height:50px;
            width:50px;
            margin: 9px;
            padding:11px ;
            border: 5px solid red;
        }
    </style>
    <script src="jquery-2.1.1.min.js"></script>
</head>
<body >
<div class="d1">
    <div class="d2"></div>
</div>
<script>
    console.log($(".d2").offset())
    console.log($(".d2").offset().top)
    console.log($(".d2").offset().left)
    console.log($(".d2").position())
offset和postion

c、尺寸

$("div").height();    //元素的高度,实际高度(不包括margin,padding,border)
$("div").width();     //元素的宽度,实际宽度(不包括margin,padding,border)

$("div").innerHeight()    //元素内部区域高度(height+上下padding)
$("div").innerWidth()     //元素内部区域宽度(width+左右padding)

$("divt").outerHeight()    //元素外部高度((height+上下padding+上下border)
$("div").outerWidth()     //元素外部宽度(width+左右padding+左右border)
$("div").outerHeight(true)    //为true时包括(margin)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div {
            height: 100px;
            width:100px;
            border: 1px solid blue;
            padding: 2px;
            margin: 4px;;
        }
    </style>
    <script src="jquery-2.1.1.min.js"></script>
</head>
<body>
<div>
</div>
<script>
    console.log($("div").height())    //100
    console.log($("div").width())    //100
    console.log($("div").innerHeight())   //104
    console.log($("div").innerWidth())   //104
    console.log($("div").outerHeight())   //106
    console.log($("div").outerWidth())  //106

</script>

</body>
</html>
尺寸样例

 

 

 3、文档处理

  a、内部插入

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

 

  b、外部插入

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

 

  c、替换

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

 

  d、删除

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

 

  e、复制

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

 

 

 四、动态效果


 1、基础动态效果

<!--基本效果-->
$("p").show()        //显示隐藏的匹配元素
$("p").show("slow");    //参数表示速度,("slow","normal","fast"),也可为1000毫秒
$("p").hide()        //隐藏显示的元素
$("p").toggle();      //切换 显示/隐藏
<!--滑动效果-->
$("p").slideDown("1000");    //用1000毫秒时间将段落滑下
$("p").slideUp("1000");     //用1000毫秒时间将段落滑上
$("p").slideToggle("1000");  //用1000毫秒时间将段落滑上,滑下
<!--淡入淡出效果-->
$("p").fadeIn("1000");        //用1000毫秒时间将段落淡入
$("p").fadeOut("1000");       //用1000毫秒时间将段落淡出
$("p").fadeToggle("1000");     //用1000毫秒时间将段落淡入,淡出
$("p").fadeTo("slow", 0.6);    //用1000毫秒时间将段落的透明度调整到0.6
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--1 隐藏与显示-->
    <!--2 淡入淡出-->
    <!--3 滑动-->
    <!--4 效果-回调:每一个动画执行完毕之后所能执行的函数方法或者所能做的一件事-->

    <p>hello</p>
    <button id="hide">隐藏</button>
    <button id="show">显示</button>
    <button id="toggle">隐藏/显示</button>

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

        $(document).ready(function(){
            $("#hide").click(function(){
                $("p").hide(1000);
            });
            $("#show").click(function(){
                $("p").show(1000);
            });

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

    </script>
</body>
</html>
隐藏和显示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #flipshow,#content,#fliphide,#toggle{
            padding: 5px;
            text-align: center;
            background-color: blueviolet;
            border:solid 1px red;

        }
        #content{
            padding: 50px;
            display: none;
        }
    </style>
</head>
<body>

    <div id="flipshow">出现</div>
    <div id="fliphide">隐藏</div>
    <div id="toggle">toggle</div>
    <div id="content">helloworld</div>

    <script src="jquery-2.1.1.min.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>

滑动
滑动效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>

      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>
      <div id="id2" style="display:none; width: 80px;height: 80px;background-color: orangered "></div>
      <div id="id3" style="display:none; width: 80px;height: 80px;background-color: darkgreen "></div>

    <script src="jquery-2.1.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#in").click(function(){
               $("#id1").fadeIn(1000);
               $("#id2").fadeIn(1000);
               $("#id3").fadeIn(1000);

            });
            $("#out").click(function(){
               $("#id1").fadeOut(1000);
               $("#id3").fadeOut(1000);
               $("#id2").fadeOut(1000);


            });
            $("#toggle").click(function(){
               $("#id1").fadeToggle(1000);
               $("#id2").fadeToggle(1000);
               $("#id3").fadeToggle(1000);

            });
            $("#fadeto").click(function(){
               $("#id1").fadeTo(1000,0.4);
               $("#id2").fadeTo(1000,0.5);
               $("#id3").fadeTo(1000,0.1);
            });
        });
    </script>
</body>
</html>

淡入淡出
淡入淡出

所有的效果都可以添加回调函数callback()。

2、自定义动画效果 

语法格式
.animate( properties [, duration ] [, easing ] [, complete ] ) .animate( properties, options ) properties:一个或多个css属性的键值对所构成的Object对象。要特别注意所有用于动画的属性必须是数字的,除非另有说明;这些属性如果不是数字的将不能使用基本的jQuery功能。比如常见的,border、margin、padding、width、height、font、left、top、right、bottom、wordSpacing等等这些都是能产生动画效果的。background
-color很明显不可以,因为参数是red或者GBG这样的值,非常用插件,否则正常情况下是不能只能动画效果的。注意,CSS 样式使用 DOM 名称(比如 "fontSize")来设置,而非 CSS 名称(比如 "font-size")。 duration动画执行的时间. easing动画运动的算法,jQuery库中是默认的时调用 swing. complete回调,动画完成时执行的函数,这个可以保证当前动画确定完成后发会触发.

 

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
    p {
        color: red;
    }
    div{
        width:200px;
        height: 100px;
        background-color: yellow;
        color:red;
    }
    </style>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <h2>animate(上)</h2>
    <p>动画效果观察</p>
    <div id="aaron">内部动画</div>
    点击观察动画效果:
    <select id="animation">
        <option value="1">动画1</option>
        <option value="2">动画2</option>
        <option value="3">动画3</option>
        <option value="4">动画4</option>
    </select>
    <input id="exec" type="button" value="执行动画">
    <script type="text/javascript">
    $("#exec").click(function() {
        var v = $("#animation").val();
        var $aaron = $("#aaron");
        if (v == "1") {
            // 数值的单位默认是px
            $aaron.animate({
                width  :300,
                height :300
            });
        } else if (v == "2") {
            // 在现有高度的基础上增加100px
            $aaron.animate({
                 width  : "+=100px",
                 height : "+=100px"
            });
        } else if (v == "3") {
            $aaron.animate({
                fontSize: "5em"
            }, 2000, function() {
                alert("动画 fontSize执行完毕!");
            });
        } else if (v == "4") {
            //通过toggle参数切换高度
            $aaron.animate({
                width: "toggle"
            });
        }
    });
    </script>
</body>

</html>
自定义动画样例

 

 

 五、事件


 

特殊的--页面载入事件

在页面载入后才开始执行脚本

$(document).ready(function(){
  代码块
});

//简写
$(function() {
  代码块
});

 

1、基本事件类型

<!--鼠标事件-->
$("p").click();      //单击事件
$("p").dblclick();    //双击事件
$("button").mousedown()//当按下鼠标时触发事件
$("button").mouseup()  //元素上放松鼠标按钮时触发事件
$("p").mousemove()     //当鼠标指针在指定的元素中移动时触发事件
$("p").mouseover()     //当鼠标指针位于元素上方时触发事件
$("p").mouseout()     //当鼠标指针从元素上移开时触发事件
$("p").foucusin()     //当元素获得焦点时,触发 focusin 事件。
$("p").focusout()     //当元素失去焦点时触发 focusout 事件。
$("p").hover(fun_mouseover,fun_mouseout)     //当鼠标移到元素上时触发fun_mouseover函数,当鼠标移出元素时触发fun_mouseout函数

<!--表单事件-->
$("input[type=text]").focus()  //元素获得焦点时,触发 focus 事件
$("input[type=text]").blur()   //元素失去焦点时,触发 blur事件
$("input").select()    //当input 元素中的文本被选择时触发事件
$("input").change()    //当元素的值发生改变时,会发生 change 事件。该事件仅适用于文本域(text field),以及 textarea 和 select 元素。
$("form").submit()     //当提交表单时触发事件

<!--键盘事件-->
$(window).keydown()    //当键盘或按钮被按下时触发事件
$(window).keypress()   //当键盘或按钮被按下时触发事件,每输入一个字符都触发一次
$("input").keyup()     //当按钮被松开时触发事件

<!--窗口和页面事件-->
$(window).scroll()     //当用户滚动时触发事件
$(window).resize()     //当调整浏览器窗口的大小时触发事件
$(window).unload()     //用户离开页面时

 

 

2、事件处理

3.0后基本只是用on替代以前的bind,live,delegate等方法,因此这里仅介绍on方法。on方法支持事件冒泡。

  a、事件绑定
  .on( events [, selector ] [, data ], handler(eventObject) )表达式
    events:一个或多个用空格分隔的事件类型和可选的命名空间,如"click"或"keydown.myPlugin" 。
    selector:一个选择器字符串用于过滤器的触发事件的选择器元素的后代。如果选择的< null或省略,当它到达选定的元素,事件总是触发。
    data:当一个事件被触发时要传递event.data给事件处理函数。
    fn:该事件被触发时执行的函数。 false 值也可以做一个函数的简写,返回false。

$("#elem").click(function(){})
<!--on绑定方式-->
$("#elem").on('click',function(){})                         //on方式
 $("#elem").on("mouseover mouseout",function(){ });         //多个事件绑定同一个函数
$("#elem").on({                                             //多个事件绑定不同函数
    mouseover:function(){},
    mouseout:function(){},
});
$("#elem").one('click',function(){})    //绑定一个一次性的事件处理函数
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
    .left div,
    .right div {
        width: 100%;
        height: 50px;
        padding: 5px;
        margin: 5px;
        float: left;
        border: 1px solid #ccc;
    }

    .left div {
        background: #bbffaa;
    }

    .right div {
        background: yellow;
    }
    </style>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <h2>on绑定多事件</h2>

    <h4>测试一</h4>
    <div class="left">
        点击触发:on('click',fn)
        <div id="test1"></div>
    </div>
    <script type="text/javascript">
    //事件绑定一
    $("#test1").on('click', function(e) {
        $(this).text('触发事件:' + e.type)
    })
    </script>


    <h4>测试二</h4>
    <div class="left">
        点击触发:on('mousedown mouseup')
        <div id="test2"></div>
    </div>
    <script type="text/javascript">
    //多事件绑定一
    $("#test2").on('mousedown mouseup', function(e) {
        $(this).text('触发事件:' + e.type)
    })
    </script>


    <h4>测试三</h4>
    <div class="right">
        点击触发:on(mousedown:fn1,mouseup:fn2)
        <div id="test3"></div>
    </div>
    <script type="text/javascript">
    //多事件绑定二
    $("#test3").on({
        mousedown: function(e) {
            $(this).text('触发事件:' + e.type)
        },
        mouseup: function(e) {
            $(this).text('触发事件:' + e.type)
        }
    })
    </script>
</body>

</html>
事件绑定样例

 

  b、事件委托

$("#elem").on('click',“p",function(){}) //事件绑定在最上层#elem元素上,当用户触发在p元素上,事件将往上冒泡,一直会冒泡在div元素上。如果提供了第二参数,那么事件在往上冒泡的过程中遇到了选择器匹配的元素,将会触发事件回调函数
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
    .left div,
    .right div {
        width: 500px;
        height: 50px;
        padding: 5px;
        margin: 5px;
        float: left;
        border: 1px solid #ccc;
    }

    .left div {
        background: #bbffaa;
    }

    .right div {
        background: yellow;
    }
    </style>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <h2>on事件委托</h2>
    <div class="left">
        <div class="aaron">
            <a>点击这里</a>
        </div>
    </div>
    <script type="text/javascript">
    //给body绑定一个click事件
    //没有直接a元素绑定点击事件
    //通过委托机制,点击a元素的时候,事件触发
    $('body').on('click', 'a', function(e) {
       alert(e.target.textContent)
    })
    </script>
</body>

</html>
事件委托样例
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
    .left div,
    .right div {
        width: 500px;
        height: 100px;
        padding: 5px;
        margin: 5px;
        float: left;
        border: 1px solid #ccc;
    }
    
    .left div {
        background: #bbffaa;
    }
    
    .right div {
        background: yellow;
    }
    </style>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <h3>事件委托,通过事件对象区别触发元素</h3>
    <div class="left">
        <div class="aaron">
            <ul>
                <li>点击:触发一</li>
                <li>点击:触发二</li>
                <li>点击:触发三</li>
                <li>点击:触发四</li>
            </ul>
        </div>
    </div>

    <script type="text/javascript">

        //多事件绑定一
        $("ul").on('click',function(e){
           alert('触发的元素是内容是: ' + e.target.textContent)
        })



    </script>

</body>


</html>
事件委托样例二

 

  c、事件解除

//假设绑定两个事件$("elem").on("mousedown mouseup",fn)
$("elem").off("mousedown")  //删除一个事件
$("elem").off("mousedown mouseup")  //删除所有事件
$("elem").off()  //删除所有事件
//假设绑定两个事件$("div").on("mousedown","p,a",fn)
$("div").off( "click", "**" ) //删除所有委托事件
$("div").off( "click", "p" ) //删除p元素委托事件

 

 3、事件对象

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

(evnet object)属性方法:
event.pageX   //事件发生时,鼠标距离网页文档(document)左上角的水平距离
event.pageY   //事件发生时,鼠标距离网页文档(document)左上角的垂直距离
event.screenX  //事件发生时,鼠标距离屏幕左上角的水平距离。
event.screenY
event.clientX  //事件发生时,鼠标距当前盒子左上角的水平距离。
event.clientY event.type   //事件的类型 event.which   //按下了哪一个键
event.timeStamp  //这个属性返回事件触发时距离1970年1月1日的毫秒数。时间戳 event.data   //在事件对象上绑定数据,然后传入事件处理函数 event.target  //事件针对的网页元素,js中事件是会冒泡的,所以this是可以变化的,但event.target不会变化,它永远是直接接受事件的目标DOM元素; event.preventDefault()  //阻止事件的默认行为(比如点击链接,会自动打开新页面) event.stopPropagation() //停止事件向上层元素冒泡
event.currentTarget    //冒泡前的当前触发事件的DOM对象, 等同于this.

 4、自定义事件

。。待补充

 

六、扩展


 

1、扩展方法

//方式一
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=radio]").uncheck();

 

2、扩展jQuery功能

//方式二
jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },    //三元运算
  max: function(a, b) { return a > b ? a : b; }
});

jQuery.min(2,3);     //2
$.max(4,5);    //5 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="title">111</div>
    <div class="title">222</div>

    <script src="jquery-2.1.1.min.js"></script>
    <script>
        jQuery.fn.extend({
            show1: function () {
                var val = this.text();
                val = val + "sb";
                return val;
            },
            show2: function () {

            }
        });
        var ret = $(".title").show1();
        console.log(ret);


        jQuery.extend({
            s1: function (arg) {
                var val = $(arg).text();
                return val + "sb";
            },
            s2: function () {

            }
        });
        var ret2 = $.s1(".title");
        console.log(ret2);
    </script>
</body>
</html>
两种扩展样例

 

七、jQuery工具函数


 

常用方法
$.trim()   //去除字符串两端的空格 $.each()   //遍历一个数组或对象,for循环,return false能跳出each循环 $.inArray() //返回一个值在数组中的索引位置,不存在返回-1


其他方法 $.grep()   //返回数组中符合某种标准的元素 $.extend() //将多个对象,合并到第一个对象 $.makeArray() //将对象转化为数组 $.type() //判断对象的类别(函数对象、日期对象、数组对象、正则对象等等 $.isArray() //判断某个参数是否为数组 $.isEmptyObject() //判断某个对象是否为空(不含有任何属性) $.isFunction() //判断某个参数是否为函数 $.isPlainObject() //判断某个参数是否为用"{}"或"new Object"建立的对象 $.support() //判断浏览器是否支持某个特性

 

八、实例部分


 

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

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

        function ReturnTop() {
            $(window).scrollTop(0);
        }
    </script>
</body>
</html>
返回顶部
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            border: 1px solid #ccc;
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
            color: white;
        }
        .menu li:hover {
            cursor: pointer;
        }
        .menu a{
            padding: 11px;
        }
        .content{
            border: 1px solid #ccc;
            height: 300px;
            font-size: 30px;
        }
        .hide{
            display: none;
        }

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

    <script src="../../jquery-1.12.4.js"></script>
    <script>
        function Tab(self) {
            $(self).addClass("current").siblings().removeClass("current");
            var x = "#" + $(self).attr("xxx");
            $(x).removeClass("hide").siblings().addClass("hide");
        }
    </script>
</body>
</html>
左侧菜单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0;
            background-color: #dddddd;
        }
        .w{
            margin: 0 auto;
            width: 980px;
        }
        .pg-header{
            background-color: black;
            color: white;
            height: 48px;
        }
        .pg-body .menu{
            position: absolute;
            left: 200px;
            width: 180px;
            background-color: white;
            float: left;
        }
        li {
            list-style-type: none;
        }
        .pg-body .menu .active{
            background-color: #425a66;
            color: white;
        }
        .pg-body .fixed{
            position: fixed;
            top: 10px;
        }
        .pg-body .content{
            position: absolute;
            left: 385px;
            right: 200px;
            background-color: white;
            float: left;
        }
        .pg-body .content .item{
            height: 900px;
            border: 1px solid green;
        }
    </style>

</head>
<body>
    <div class="pg-header">
        <div class="w"></div>
    </div>
    <div class="pg-body">
        <div id="menu" class="menu">
            <ul>
                <li menu="funcOne">第一章</li>
                <li menu="funcTwo">第二章</li>
                <li menu="funcStree">第三章</li>
            </ul>
        </div>
        <div id="content" class="content">
            <div class="item" con="funcOne">床前明月光</div>
            <div class="item" con="funcTwo">疑是地上霜</div>
            <div class="item" con="funcStree" style="height: 100px">我是郭德纲</div>
        </div>
    </div>

    <script src="jquery-2.1.1.min.js"></script>
    <script>
        window.onscroll = function () {
            //滚轮下滑,菜单固定
            var scrTop = $(window).scrollTop();
            if (scrTop >= 48){
                $("#menu").addClass("fixed");
            }else {
                $("#menu").removeClass("fixed");
            }


            var windowHeight = $(window).height();    //视窗高度
            $(".item").each(function () {
                var itemTopOffset = $(this).offset().top;    //章节顶部离文档顶部距离
                var itemBotOffset = $(this).height() + itemTopOffset;   //章节底部离文档顶部距离
                var menuCon = $(this).attr("con");

                //进入正常章节条件判断
                if ((itemTopOffset < scrTop) && (scrTop < itemBotOffset)){
                    $("ul [menu='" + menuCon +"']").addClass("active").siblings().removeClass("active");
                    return false    //return false才能跳出each循环。
                }
            })

            //判断是否已经到达文档底部,如果到达底部,就激活最后一章标签。
            if ((windowHeight + scrTop) == $(document).height()){
                $("ul .active").removeClass("active");
                $("li:last").addClass("active");

            }


        }
    </script>
</body>
</html>
滚动菜单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            border: 1px solid #ccc;
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
            color: white;
        }
        .menu li:hover {
            cursor: pointer;
        }
        .menu a{
            padding: 11px;
        }
        .content{
            border: 1px solid #ccc;
            height: 300px;
            font-size: 30px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: #0099dd;
            color: black;
        }
    </style>
</head>
<body>
    <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current">菜单一</li>
              <li xxx="c2" >菜单二</li>
              <li xxx="c3" >菜单三</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-2.1.1.min.js"></script>
    <script>
//方法一,直接绑定在元素上
//        $("li[xxx]").on("click",function () {
//            $(this).addClass("current").siblings().removeClass("current");
//            var x = "#" + $(this).attr("xxx");
//            $(x).removeClass("hide").siblings().addClass("hide");
//
//        })
//方法二,绑定在父元素上,冒泡事件e.target相当晕上面方法的this
        $("ul").on("click",function (e) {
            console.log(e.target)
            $(e.target).addClass("current").siblings().removeClass("current");
            var x = "#" + $(e.target).attr("xxx");
            $(x).removeClass("hide").siblings().addClass("hide");

        })

    </script>
</body>
</html>
TAB菜单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--onclick="Add(this);"-->
</head>
<body>
<div class="outer">
           <div class="section">
               <div class="icons" style="display: inline-block">
                   <a ><button>+</button></a>
               </div>
               <div class="inputs" style="display: inline-block">
                   <input type="checkbox">
                   <input type="text" value="IP">
               </div>
           </div>
       </div>

    <script src="jquery-2.1.1.min.js"></script>
    <script>
//        $(".outer .section").on("click","button",function () {
//            //parentsUntil(".outer")包括了多个父元素,因此需要.last()来选择最外层的父元素。
//            //.end() 方法结束当前链条中的最近的筛选操作,并将匹配元素集还原为之前的状态。
//            $(this).parentsUntil(".outer").last().clone().find("button").text("-").attr("onclick","Remove(this);").end().appendTo(".outer")
//        })
//        function Remove(self) {
//            $(self).parentsUntil(".outer").last().remove()
//        }
          $("button").on("click",function () {
               $(this).parentsUntil(".outer").last().clone().find("button").text("-").attr("onclick","Remove(this);").end().appendTo(".outer")
          })
        function Remove(self) {
            $(self).parentsUntil(".outer").last().remove()
        }

    </script>
</body>
</html>
添加删除元素并绑定事件
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div style="border: 1px solid #ddd;width: 600px;position: absolute;">
        <div id="title" style="background-color: black;height: 40px;color: white;">
            <strong>标题</strong>
        </div>
        <div style="height: 300px;">
            内容
        </div>
    </div>
<script src="jquery-2.1.1.min.js"></script>
<script>
    $(function () {
        $('#title').mouseover(function () {
            $(this).css('cursor','move');
        }).mousedown(function (e) {
            var _event = e || widows.event;
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;

            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;
            //鼠标点击时绑定,鼠标移动事件
            $(this).on('mousemove',function (e) {
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;

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

                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');
            })
        }).mouseup(function () {
            $(this).off('mousemove');
        });
    })
</script>
</body>
</html>
拖动面板
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .shade{
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,.6) ;
            z-index: 20;
        }
        .modal{
            position: fixed;
            left: 50%;
            top: 50%;
            height: 300px;
            width: 400px;
            margin-top: -150px;
            margin-left: -200px;
            z-index: 30;
            border: 1px solid #ddd;
            background-color: white;
        }
        .hide{
            display: none;
        }
        .modal form {
            position: fixed;
            left: 50%;
            top: 50%;
            height: 200px;
            width: 229px;
            border: 1px;
            margin-left: -115px;
            margin-top: -100px;
        }
        .modal form p {
            float: right;
            margin-top: 12px;
        }
        .modal form span {
            float: right;
            display: inline-block;
            height: 18px;
            width: 170px;
            background-color: #FFEBEB;
            text-align: center;
            border: 1px solid #ffbdbe;
            color: #e4393c;
            font-size: 14px;
            visibility: hidden;
        }
        .modal form [type="button"] {
            position: absolute;
            bottom: -30px;
            left: 115px;
        }
        .modal form [value="提交"]{
            left: 50px;
        }
        .edit_btn:hover{
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div style="width: 300px; margin: 0 auto">
        <input type="button" value="添加主机" onclick="return Add();" />
        <table style="border: 2px solid #F5F5F5; width: 300px;">
            <thead>
                <tr>
                    <th >主机名</th>
                    <th >IP</th>
                    <th >端口</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="host-list">
                <tr>
                    <td target="host">c1.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td class="edit_btn">Edit</td>
                </tr>
               <tr>
                    <td target="host">c2.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td class="edit_btn">Edit</td>
                </tr>
                <tr>
                    <td target="host">c3.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td class="edit_btn">Edit</td>
                </tr>
                <tr>
                    <td target="host">4.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td class="edit_btn">Edit</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="shade hide"></div>
    <div  class="modal hide">
        <form action="" method="get">
            <p>主机名:<input type="text" id="host" name="host"><br><span></span></p>
            <p>IP地址:<input type="text" id='ip' name="ip"><br><span></span></p>
            <p>端口号:<input type="text" id='port' name="port"><br><span></span><br></p>
            <input type="button" value="提交" onclick="SubmitForm();">
            <input type="button" value="取消" onclick="HideModal();">
        </form>
    </div>

    <script src="jquery-2.1.1.min.js"></script>
    <script>
        add_status = false  //是否是新增主机的标志
        //在表格上绑定冒泡事件,使新增的行也能有委托事件。弹出模态框
        $("#host-list").on("click",".edit_btn", function () {
            $(".shade,.modal").removeClass("hide");
            prevList = $(this).prevAll();
            prevList.each(function () {
                var text = $(this).text();
                var target = $(this).attr("target");
                $("#"+target).val(text);
            });
        })
        //新增主机弹出模态框。
        function Add() {
            add_status=true//新增一个标志判断是否是新增主机。
            $(".shade,.modal").removeClass("hide");

        }
        //关闭模态框,并清空模态框已输入的内容。
        function HideModal() {
            $(".shade,.modal").addClass("hide");
            $(".modal").find("input[type='text']").val("");

        }

        //提交模态框内容
        function SubmitForm() {
            //判断表单信息是否合规。这里判断是否为空
            flag=Validate($(".modal input[type='text']"))
            //新增主机
            if (add_status && flag){
                $("tbody").append($("tr").last().clone());
                $(".modal").find("input[type='text']").each(function () {
                    var value = $(this).val();
                    var name = $(this).attr("name");
                    ($("tr").last().children()).each(function () {
                        if ($(this).attr("target") == name){
                            $(this).text(value);
                        }
                            }
                    )});
                HideModal();
                add_status = false;//重置新增主机标志
                return false;
            }

            //编辑主机信息
            if (flag){
                $(".modal").find("input[type='text']").each(function () {
                    var value = $(this).val();
                    var name = $(this).attr("name");
                    $(prevList).each(function () {
                        if ($(this).attr("target") == name){
                            $(this).text(value);
                        }
                            }
                    )});
                    $(".modal,.shade").addClass("hide");
                    HideModal();
                }
            }

        //表单验证函数
        function Validate(sel) {
            var valid=true
            sel.each(function () {
                var val =$.trim($(this).val())
                if(!val){
                    valid=false
                    return false    //跳出each循环
                }
            })
            return valid
        }
    </script>
</body>
</html>
模态编辑框新增和修改数据+简单表单验证
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .hide{
            display:none;
        }
        .header-nav {
            height: 39px;
            background: #c9033b;
        }
        .header-nav .bg{
            background: #c9033b;
        }
        .header-nav .nav-allgoods .menuEvent {
            display: block;
            height: 39px;
            line-height: 39px;
            text-decoration: none;
            color: #fff;
            text-align: center;
            font-weight: bold;
            font-family: 微软雅黑;
            color: #fff;
            width: 100px;
        }
        .header-nav .nav-allgoods .menuEvent .catName {
            height: 39px;
            line-height: 39px;
            font-size: 15px;
        }
        .header-nav .nav-allmenu a {
            display: inline-block;
            height: 39px;
            vertical-align: top;
            padding: 0 15px;
            text-decoration: none;
            color: #fff;
            float: left;
        }
        .header-menu a{
            color:#656565;
        }
        .header-menu .menu-catagory{
            position: absolute;
            background-color: #fff;
            border-left:1px solid #fff;
            height: 316px;
            width: 230px;
             z-index: 4;
             float: left;
        }
        .header-menu .menu-catagory .catagory {
            border-left:4px solid #fff;
            height: 104px;
            border-bottom: solid 1px #eaeaea;
        }
        .header-menu .menu-catagory .catagory:hover {
            height: 102px;
            border-left:4px solid #c9033b;
            border-bottom: solid 1px #bcbcbc;
            border-top: solid 1px #bcbcbc;
        }
        .header-menu .menu-content .item{
            margin-left:230px;
            position:absolute;
            background-color:white;
            height:314px;
            width:500px;
            z-index:4;
            float:left;
            border: solid 1px #bcbcbc;
            border-left:0;
            box-shadow: 1px 1px 5px #999;
        }
    </style>
</head>
<body>
    <div class="pg-header">

    <div class="header-nav">
        <div class="container narrow bg">
            <div class="nav-allgoods left">
                <a id="all_menu_catagory" href="#" class="menuEvent">
                    <b class="catName">全部商品分类</b>>
                    <span class="arrow" style="display: inline-block;vertical-align: top;"></span>
                </a>
            </div>
        </div>
    </div>
    <div class="header-menu">
        <div class="container narrow hide">
            <div id="nav_all_menu" class="menu-catagory">
                <div class="catagory" float-content="one">
                    <div class="title">家电</div>
                    <div class="body">
                        <a href="#">空调</a>
                    </div>
                </div>
                <div class="catagory" float-content="two">
                    <div class="title">床上用品</div>
                    <div class="body">
                        <a href="http://www.baidu.com">床单</a>
                    </div>
                </div>
                <div class="catagory" float-content="three">
                    <div class="title">水果</div>
                    <div class="body">
                        <a href="#">橘子</a>
                    </div>
                </div>
            </div>

            <div id="nav_all_content" class="menu-content">
                <div class="item hide" float-id="one">

                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="勺子">勺子</a> </span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="菜刀">菜刀</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#">菜板</a> </span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="碗">碗</a> </span>

                        </dd>
                    </dl>

                </div>
                <div class="item hide" float-id="two">
                    <dl>
                        <dt><a href="#" class="red">床上用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="">枕头</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">床上用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">夏凉被</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">床上用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">嘿嘿嘿</a> </span>

                        </dd>
                    </dl>
                </div>
                <div class="item hide" float-id="three">
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">微波炉</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="http://www.meilele.com/category-jiaofa" target="_blank" title="角阀">金菜刀</a> </span>

                        </dd>
                    </dl>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="jquery-2.1.1.min.js"></script>
<script>
    $(function () {
        Change("#all_menu_catagory","#nav_all_menu","#nav_all_content")
    });

    function Change(menuF,menuS,menuT) {
        $(menuF).bind({
            "mouseover":function () {
            $(menuS).parent().removeClass("hide");
        },"mouseout":function () {
            $(menuS).parent().addClass("hide");
        }
        });

        $(menuS).children().bind({
            "mouseover":function () {
                $(menuS).parent().removeClass("hide");
                var $item = $(menuT).find('[float-id="' + $(this).attr("float-content") + '"]');
                $item.removeClass("hide").siblings().addClass("hide");
            },
            "mouseout":function () {
                $(menuS).parent().addClass("hide");
                $(menuT).parent().addClass("hide");
            }
        });

        $(menuT).children().bind({
            "mouseover":function () {
                $(menuS).parent().removeClass("hide");
                $(this).removeClass("hide");
            },
            "mouseout":function () {
                $(menuS).parent().addClass("hide");
                $(this).addClass("hide");
            }
        })
    }
</script>
</body>
</html>
商城的折叠菜单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        ul{
            list-style: none;
        }
        .out{
            width: 730px;
            height: 454px;
            margin: 50px auto;
            position: relative;
        }
        .out .img li{
            position: absolute;
            left: 0;
            top: 0;
        }
        .out .num{
            position: absolute;
            left:0;
            bottom: 20px;
            text-align: center;
            font-size: 0;
            width: 100%;
        }
        .out .btn{
            position: absolute;
            top:50%;
            margin-top: -30px;
            width: 30px;
            height: 60px;
            background-color: aliceblue;
            color: black;
            text-align: center;
            line-height: 60px;
            font-size: 40px;
            display: none;
        }
        .out .num li{
            width: 20px;
            height: 20px;
            background-color: black;
            color: #fff;
            text-align: center;
            line-height: 20px;
            border-radius: 60%;
            display: inline;
            font-size: 18px;
            margin: 0 10px;
            cursor: pointer;
        }
        .out .num li.active{
            background-color: red;
        }
        .out .left{
            left: 0;
        }
        .out .right{
            right: 0;
        }
        .out:hover .btn{
            display: block;
            color: white;
            font-weight: 900;
            background-color: black;
            opacity: 0.6;
            cursor: pointer;
        }
        .out img {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
     <div class="out">
         <ul class="img">
             <li><a href="#"><img src="images/1.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/2.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/3.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/4.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/5.jpg" alt=""></a></li>
         </ul>

         <ul class="num">
         </ul>

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

     </div>

    <script src="jquery-2.1.1.min.js"></script>
    <script>
        $(function(){
            //根据图片数量动态添加圆点
            var size=$(".img li").size();
            for (var i= 1;i<=size;i++){
                var li="<li>"+i+"</li>";
                $(".num").append(li);
            }
            //首先激活第一个圆点图片
            $(".num li").eq(0).addClass("active");

            //圆点滑动,展现相应图片
            $(".num li").mouseover(function(){
               $(this).addClass("active").siblings().removeClass("active");
               var index=$(this).index();
               i=index;
               $(".img li").eq(index).fadeIn(1000).siblings().fadeOut(1000);
            });

        //开启自动循环定时器
        var t=setInterval(move,1500);

        //展现下一张图片
        i=0;
        function move(){
            i++;
            if(i==size){
                i=0;//滑到最后一个从头开始
            }
            $(".num li").eq(i).addClass("active").siblings().removeClass("active");
            $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
        }
        //展现上一张图片
        function moveL(){
            i--;
            if(i==-1){
                i=size-1;
            }
            $(".num li").eq(i).addClass("active").siblings().removeClass("active");
            $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
        }
          //鼠标滑动到图片,停止定时器循环。鼠标离开继续循环。
        $(".out").hover(function(){
            clearInterval(t);
        },function(){
            t=setInterval(move,1500);
        });

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

        });
    </script>

</body>
</html>
轮播图
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>放大镜</title>
    <style>
        .content{
            position: relative;
        }
        .small-box{
            width: 350px;
            height: 350px;
            border: 2px solid blue;
            position: absolute;
            top:0;
            left:0;
        }
        .mask-layer{
            width: 175px;
            height: 175px;
            background-color: yellowgreen;
            opacity:0.5;
            position: absolute;
            top:0;
            left:0;
            display: none;
        }
        .big-box{
            height:400px;
            width:400px;
            position: absolute;
            left:354px;
            border:2px dashed red;
            overflow: hidden;
            display: none;

        }
        .big-img {
            position: absolute;


        }
    </style>
</head>

<body>
<div class="content">
    <div class="small-box">
        <img class="small-img" src="images/small.jpg">
        <div class="mask-layer"></div>
    </div>
    <div class="big-box">
        <img class="big-img" src="images/big.jpg" >
    </div>


</div>




<script src="jquery-2.1.1.min.js"></script>
<script>
    //鼠标滑入小图显示mask-layer和big-box,数遍滑出隐藏
    $(".small-box").mouseover(function () {
        $(".mask-layer").css("display","block")
        $(".big-box").css("display","block")
    }).mouseout(function () {
        $(".mask-layer").css("display","none")
        $(".big-box").css("display","none")
    })


    //限制mask-layer遮罩层移动范围在小图内部,以遮罩层中心点距离各边的范围限制。
    $(".small-box").mousemove(function (e) {
        var _event = e || window.event;  //兼容多个浏览器的event参数模式
        var mask_layer_width=$(".mask-layer").width()
        var mask_layer_height=$(".mask-layer").height()
        var half_width_mask_layer=mask_layer_width/2
        var half_width_mask_layer=mask_layer_height/2
        var small_box_width=$(this).width()
        var small_box_height=$(this).height()
        //mask-layer需要偏移的距离
        var X_offset=e.clientX-half_width_mask_layer
        var Y_offset=e.clientY-half_width_mask_layer
        if(X_offset<0){
            X_offset=0
        }else if(X_offset>(small_box_width-$(".mask-layer").width())){
            X_offset=small_box_width-$(".mask-layer").width()
        }
        if(Y_offset<0){
            Y_offset=0
        }else if(Y_offset>(small_box_height-$(".mask-layer").height())){
            Y_offset=small_box_height-$(".mask-layer").height()
        }
        $(".mask-layer").css("left",X_offset+"px")
        $(".mask-layer").css("top",Y_offset+"px")

        //大图移动的距离和小图移动的距离成比例,反向运动。比例为,大图可偏移动距离/小图可偏移距离
        var X_percent=($(".big-img").width()-$(".big-box").width())/(small_box_width-mask_layer_width)
        var Y_percent=($(".big-img").height()-$(".big-box").height())/(small_box_height-mask_layer_height)
        big_X_offset=-X_offset*X_percent
        big_Y_offset=-Y_offset*Y_percent
        $(".big-img").css("left",big_X_offset+"px")
        $(".big-img").css("top", big_Y_offset+"px")

    })


</script>
</body>
</html>
商品放大镜

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

posted on 2016-08-17 14:54  苍松  阅读(325)  评论(0编辑  收藏  举报

导航