JQuery~1

本节内容:

1: jQuery是什么?

2:什么是jQuery对象?

3:寻找元素(选择器和筛选器) 

4: 操作元素(属性,css,文档处理)

5: jQuery节点的增删改查

6:css操作

7:事件

8:动画效果

9:扩展方法 (插件机制)

10:轮播图

 

 

jQuery文档:http://jquery.cuishifeng.cn/ 

1: jQuery是什么?

<1> jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。

<2>jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

<3>它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器

<4>jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。

<5>jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。

2:什么是jQuery对象?

jquery的基础语法:$(selector).action()

jQuery 对象就是通过jQuery包装DOM对象后产生的对象。jQuery 对象是 jQuery 独有的

如果一个对象是 jQuery 对象那么它就可以使用 jQuery 里的方法: $(“#test”).html();

$("#test").html()    
       //意思是指:获取ID为test的元素内的html代码。其中html()是jQuery里的方法 

       // 这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML; 

       //虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错

       //约定:如果获取的是 jQuery 对象, 那么要在变量前面加上$. 

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

$variable[0]:jquery对象转为dom对象      $("#msg").html(); $("#msg")[0].innerHTML

3:寻找元素(选择器和筛选器) 

3.1   选择器

3.1.1 基本选择器      

$("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")

3.1.2 层级选择器      

$(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")
E F    后代元素选择器,匹配所有属于E元素后代的F元素,E和F之间用空格分隔    
E > F  子元素选择器,匹配所有E元素的子元素F                            
E + F  毗邻元素选择器,匹配所有紧随E元素之后的同级元素F 
E~F   匹配 prev 元素之后的所有 siblings 元素

###################E~F ################
找到所有与表单同辈的 input 元素
HTML 代码:
    <form>
      <label>Name:</label>
      <input name="name" />
      <fieldset>
          <label>Newsletter:</label>
          <input name="newsletter" />
     </fieldset>
    </form>
    <input name="none" />
    
jQuery 代码:
    $("form ~ input")
结果:
    [ <input name="none" /> ]

#######################E~F ##########
View Code

3.1.3 基本筛选器      

$("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")

3.1.4 属性选择器    

$('[id="div1"]')   $('["alex="sb"][id='p1']') ##一个属性不够,来两个

3.1.5 表单选择器     

$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")
<TABLE>
    <input type="text">
</TABLE>
<script>
    //表单选择器
    //$("[type='text']").css("width","200px")
    $(":text").css("width","400px")
</script>
View Code

筛选器 根据已知的找到需要的元素。跟js的导航一样

查找筛选器:这个比刚刚的更好一点 

<body>

<ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>4444</li>
</ul>

<script>
    //两种是一样的。第一种写在里面不灵活,要是eq是动态的呢?你还得去字符串拼接
    //$("li:eq(2)").css("color","red");
    //$("li").eq(3).css("color","blue");
    $("li").first().css("color","red");
    $("li").last().css("color","red");

</script>
View Code
 $("div").children(".test")     $("div").find(".test")  
                               
 $(".test").next()    $(".test").nextAll()    $(".test").nextUntil("#end") 
                           
 $("div").prev()  $("div").prevAll()  $("div").prevUntil()   
                        
 $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 

 $("div").siblings()

4: 操作元素(属性,css,文档处理)

-------------------------属性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------CSS类
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------HTML代码/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])  //固有属性采用val()
---------------------------
$("").css("color","red")   //ele2.css({"color":"red","background-color":"green"})

实例之左侧菜单

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

    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              float: left;
          }
         .title{
             line-height: 50px;
             background-color: #425a66;
             color: forestgreen;}


         .hide{
             display: none;
         }


    </style>
</head>
<body>

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

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

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

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


</body>
</html>
View Code

属性操作:attr和prop的区别

<input id="chk1" type="checkbox" />是否可见
<input id="chk2" type="checkbox" checked="checked" />是否可见



<script>

//对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
//对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
//像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此
//需要使用prop方法去操作才能获得正确的结果。


//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    false

//  ---------手动选中的时候attr()获得到没有意义的undefined-----------
//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    true

    console.log($("#chk1").prop("checked"));//false
    console.log($("#chk2").prop("checked"));//true
    console.log($("#chk1").attr("checked"));//undefined
    console.log($("#chk2").attr("checked"));//checked
</script>

attr和prop
View Code

 实例之全反选

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

             function selectall(){

                 $("table :checkbox").prop("checked",true)
             }
             function cancel(){

                 $("table :checkbox").prop("checked",false)
             }

             function reverse(){


                 //                 var idlist=$("table :checkbox")
//                 for(var i=0;i<idlist.length;i++){
//                     var element=idlist[i];
//
//                     var ischecked=$(element).prop("checked")
//                     if (ischecked){
//                         $(element).prop("checked",false)
//                     }
//                     else {
//                         $(element).prop("checked",true)
//                     }
//
//                 }
//    jquery循环的两种方式
                 //方式一
//                 li=[10,20,30,40]
//                 dic={name:"yuan",sex:"male"}
//                 $.each(li,function(i,x){
//                     console.log(i,x)
//                 })

                 //方式二
//                    $("tr").each(function(){
//                        console.log($(this).html())
//                    })



                 $("table :checkbox").each(function(){

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

//                     if ($(this).prop("checked")){
//                         $(this).prop("checked",false)
//                     }
//                     else {
//                         $(this).prop("checked",true)
//                     }

                     // 思考:如果用attr方法可以实现吗?


                 });
             }

    </script>
</head>
<body>

     <button onclick="selectall();">全选</button>
     <button onclick="cancel();">取消</button>
     <button onclick="reverse();">反选</button>

     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
         </tr>
     </table>



</body>
</html>
View Code

 实例之模态对话框

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

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

        .hide{
            display: none;
        }

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

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

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


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

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

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

        $(self).parent().addClass("hide").prev().addClass("hide") //支持链式操作  

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

5: jQuery节点的增删改查

内部插入

$("").append(content|fn)      ----->$("p").append("<b>Hello</b>");
$("").appendTo(content)       ----->$("p").appendTo("div");
$("").prepend(content|fn)     ----->$("p").prepend("<b>Hello</b>");
$("").prependTo(content)      ----->$("p").prependTo("#foo");
<div class="parent">
    <p>ppp</p>
</div>
<input type="button" value="添加"></input>

<script src="jquery-3.3.1.min.js"></script>
<script>
    $(":button").click(function () {
        //第一种直接添加
        // $('.parent').append("<h2>helloworld</h2>")

        //第二种添加
        var ele = $("<h2></h2>"); //相当于js的createElement
        ele.css("color","red");
        ele.html("hello world");
        // $(".parent").append(ele);

        //ele.appendTo($(".parent")); //将自己添加到父亲里面去

        $(".parent").prepend(ele);
        //ele.prependTo($(".parent"))
    })
</script>
View Code

外部插入

$("").after(content|fn) ----->$("p").after("<b>Hello</b>");  //不再是按儿子去插入,而是按兄弟去插入
$("").before(content|fn) ----->$("p").before("<b>Hello</b>");
$("").insertAfter(content) ----->$("p").insertAfter("#foo");
$("").insertBefore(content) ----->$("p").insertBefore("#foo");
/替换
    $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>");

//删除

    $("").empty()  //是把标签里面的内容清空
    $("").remove([expr]) //把标签移除

//复制

    $("").clone([Even[,deepEven]])
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<div class="c1">
    <p>PPP</p>

</div>

<button>add</button>
<script src="jquery-3.1.1.js"></script>
<script>
        $("button").click(function () {
           //$(".c1").append("<h1>HELLO YUAN</h1>")

            var $ele=$("<h1></h1>");
            $ele.html("HELLO WORLD!");
            $ele.css("color","red");

//内部插入
            //$(".c1").append($ele);
            //$ele.appendTo(".c1")
            //$(".c1").prepend($ele);
            //$ele.prependTo(".c1")

//外部插入
            //$(".c1").after($ele)
            //$ele.insertAfter(".c1")
            //$(".c1").before($ele)
            //$ele.insertBefore(".c1")
//替换
             //$("p").replaceWith($ele)

//删除与清空
            //$(".c1").empty()
            //$(".c1").remove()

//clone
//             var $ele2= $(".c1").clone();
//             $(".c1").after($ele2)
        })
</script>
</body>
</html>
实现操作

 实例之复制样式条

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

</head>
<body>
            <div class="outer">
                <div class="item">
                        <input type="button" value="+" onclick="add(this);">
                        <input type="text">
                </div>
            </div>

<script src="jquery-3.3.1.min.js"></script>
    <script>
            //var $clone_obj=$(self).parent().clone();  // $clone_obj放在这个位置可以吗?
            function add(self){
                // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
                 var $clone_obj=$(self).parent().clone();
                 $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
                 $(self).parent().parent().append($clone_obj);
            }
           function removed(self){

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

           }

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

6:css操作

CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])
        $("").position()
        $("").scrollTop([val])  //设置或获取滚轮的高度
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])  //获取或设置content的高度
        $("").width([val|fn])  //获取或设置content的宽度
        $("").innerHeight()  //包含了padding
        $("").innerWidth()
        $("").outerHeight([soptions]) //包含padding和border 设置为 true 时,计算边距在内。
        $("").outerWidth([options])

实例返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div2{
            width: 100%;
            height: 800px;
        }
        .div1{
            width: 40%;
            height: 150px;
            background-color: antiquewhite;
            overflow: auto;
        }
        .div2{
            background-color: rebeccapurple;
        }

         .returnTop{
             position: fixed;
             right: 20px;
             bottom: 20px;
             width: 90px;
             height: 50px;
             background-color: gray;
             color: white;
             text-align: center;
             line-height: 50px;
         }

         .hide{
             display: none;
         }

    </style>
</head>
<body>


<div class="div1">
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
</div>

<div class="div2">
    <button onclick="returnTop()">return</button>
</div>

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

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


    window.onscroll=function () {


//        console.log($(window).scrollTop());

        if($(window).scrollTop()>300){
            $(".returnTop").removeClass("hide")
        }else {
            $(".returnTop").addClass("hide")
        }


    };

    function returnTop() {
        $(window).scrollTop(0)

    }

    $(".div2 button").click(function () {
         $(".div1").scrollTop(0)
    })



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

7:事件

页面载入
    ready(fn)  //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
    $(document).ready(function(){}) -----------> $(function(){})

事件处理
    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。

    //  .on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如:
    //  $('ul').on('click', 'li', function(){console.log('click');})就是筛选出ul下的li给其绑定
    //  click事件;

    [selector]参数的好处:
        好处在于.on方法为动态添加的元素也能绑上指定事件;如:

        //$('ul li').on('click', function(){console.log('click');})的绑定方式和
        //$('ul li').bind('click', function(){console.log('click');})一样;我通过js给ul添加了一个
        //li:$('ul').append('<li>js new li<li>');这个新加的li是不会被绑上click事件的

        //但是用$('ul').on('click', 'li', function(){console.log('click');}方式绑定,然后动态添加
        //li:$('ul').append('<li>js new li<li>');这个新生成的li被绑上了click事件
    
    [data]参数的调用:
             function myHandler(event) {
                alert(event.data.foo);
                }
             $("li").on("click", {foo: "bar"}, myHandler)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

<script src="jquery-3.1.1.js"></script>
<script>
    // 事件准备加载方式一
//    $(document).ready(function () {
//         $("ul li").html(5);
//    });
// 事件准备加载方式二
     $(function () {
        $("ul li").html(5);
     });

//事件绑定简单形式
//    var eles=document.getElementsByTagName("li")
//    eles.onclick=function () {
//        alert(123)
//    }

//    $("ul li").click(function () {
//        alert(6666)
//    });

//    $("ul li").bind("click",function () {
//        alert(777)
//    });

    //事件委托
//    $('ul').on("click","li",function () {
//       alert(999);
//    });
//
//    $("button").click(function () {
//
//            var $ele=$("<li>");
//            var len=$("ul li").length;
//            $ele.html((len+1)*1111);
//            $("ul").append($ele)
//    });
   // $("ul li").unbind("click")

</script>
</head>
<body>

<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
</ul>

<button>add</button>

</body>
</html>
View Code

8:动画效果

显示和隐藏 show、hide

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


</style>
<body>

<div class="div1">hello</div>

<button onclick="f1()">显示</button>
<button onclick="f2()">隐藏</button>
<button onclick="f3()">切换</button>
<script>
    function f1() {
        $(".div1").show(1000); //有参数是毫秒单位  用1秒才完成这个显示的动作
    }
    function f2() {
        $(".div1").hide();
    }
    function f3() {
        $(".div1").toggle(); //如果当前是show,就hide ,如果是hide 就show
    }


</script>

</body>
</html>
View Code

滑动 slideUp 、slideDown

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

        #content{
            text-align: center;
            background-color: lightblue;
            border:solid 1px red;
           
            padding: 50px;
        }
    </style>
</head>
<body>

    <div id="slideDown">出现</div>
    <div id="slideUp">隐藏</div>
    <div id="slideToggle">toggle</div>

    <div id="content">helloworld</div>
    
 <script>
    $(document).ready(function(){
     $("#slideDown").click(function(){
         $("#content").slideDown(1000);
     });
      $("#slideUp").click(function(){
         $("#content").slideUp(1000);
     });
      $("#slideToggle").click(function(){
         $("#content").slideToggle(1000);
     })
  });
    </script>
</body>
</html>
View Code

淡入淡出 [根据颜色的深浅来]。fadein、fadeout、

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
    $(document).ready(function(){
   $("#in").click(function(){
       $("#id1").fadeIn(1000);


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

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


   });
    $("#fadeto").click(function(){
       $("#id1").fadeTo(1000,0.4); //从调到0.4

   });
});



    </script>

</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=" width: 80px;height: 80px;background-color: blueviolet"></div>

</body>
</html>
View Code

回调函数

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


</style>
<body>

<div class="div1">hello</div>

<button onclick="f1()">显示</button>
<button onclick="f2()">隐藏</button>
<button onclick="f3()">切换</button>
<script>
    function f1() {
        $(".div1").show(1000); //有参数是毫秒单位  用1秒才完成这个显示的动作
    }
    function f2() {   //回调函数,就是执行完成后,再执行回调函数
        $(".div1").hide(1000,function () {
            alert("隐藏成功")
        });
    }
    function f3() {
        $(".div1").toggle(); //如果当前是show,就hide ,如果是hide 就show
    }


</script>

</body>
</html>
View Code

 9:扩展方法 (插件机制)

<script>
    
$.extend(object)      //为JQuery 添加一个静态方法。
$.fn.extend(object)   //为JQuery实例添加一个方法。


    jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
        });
    console.log($.min(3,4));

//-----------------------------------------------------------------------

$.fn.extend({
    "print":function(){
        for (var i=0;i<this.length;i++){
            console.log($(this)[i].innerHTML)
        }

    }
});

$("p").print();
</script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.1.1.js"></script>
    <title>Title</title>
</head>
<body>

<p>111</p>
<p>222</p>
<p>333</p>

<script>



//    $.each(obj,function () {
//
//    });
//
//    $("").each(function () {
//
//    })


    $.extend({
        Myprint:function () {
            console.log("hello")
        }
    });

//    $.Myprint();

    $.fn.extend({
        GetText:function () {
//            for(var i=0;i<this.length;i++){
//                console.log(this[i].innerHTML)
//            }

            $.each($(this),function (x,y) {

                //console.log(y.innerHTML)
                //console.log($(y).html())
            })

        }
    });

    $("p").GetText()

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

 10:轮播图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .outer {
        width:590px ;
        height:470px ;
        margin: 80px auto;
        position: relative;
    }
    .img li {
        list-style: none;
        position: absolute;
        top: 0;
        left: 0;
    }
    .num {
        position: absolute;
        bottom: 20px;
        left: 180px;
        list-style: none;
    }
    .num li {
        display: inline-block;
        width: 20px;
        height: 20px;
        background-color: white;
        border-radius: 50%;
        text-align: center;
        line-height: 20px;
        margin-left: 8px;
    }
    .btn {
        position: absolute;
        width: 30px;
        height: 60px;
        background-color: green;
        color: white;
        text-align: center;
        line-height: 60px;
        font-size: 30px;
        opacity: 0.7;
        top: 50%;
        margin-top: -30px;
        display: none;
    }
    .left {
        left: 0;
    }
    .right{
        right: 0;
    }
    .outer:hover .btn {
        display: block;
    }
    .outer .num .active {
        background-color: red;
    }
</style>
<body>

<div class="outer">
   <ul class="img">
       <li><a href=""><img src="images/1.jpg" alt=""></a></li>
       <li><a href=""><img src="images/2.jpg" alt=""></a></li>
       <li><a href=""><img src="images/3.jpg" alt=""></a></li>
       <li><a href=""><img src="images/4.jpg" alt=""></a></li>
       <li><a href=""><img src="images/5.jpg" alt=""></a></li>
   </ul>

    <ul class="num">
        <!--<li class="active"></li>-->
        <!--<li></li>-->
        <!--<li></li>-->
        <!--<li></li>-->
        <!--<li></li>-->
    </ul>
    <div class="left btn"><</div>
    <div class="right btn">></div>
</div>

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

<script>
    var i = 0 ;
    // 通过jquery自动创建图片对应的按钮标签
    var img_num = $(".img li").length;
    for (var j=0;j<img_num;j++){
         $(".num").append("<li></li>")
    }
    $(".num li").eq(0).addClass("active");

    //手动轮播按钮  悬浮按钮的时候出现对应的图片
    $(".num li").mouseover(function () {
       i = $(this).index();
       $(this).addClass("active").siblings().removeClass("active");
       $(".img li").eq(i).stop().fadeIn(1000);  //stop的意思是在我fadein的时候,先把前面的fadein或者fadeout都停止了!
       $(".img li").eq(i).siblings().stop().fadeOut(1000);
       console.log(index)
    });

    //自动轮播
    var clock ;
    clock = setInterval(Go_right,2000);

    function Go_right() {
        if (i == img_num-1){ //因为索引是从0开始的
           i=-1;
        }
        i++;
        $(".num li").eq(i).addClass("active").siblings().removeClass("active");
        $(".img li").eq(i).stop().fadeIn().siblings().stop().fadeOut();
    }
    $(".outer").hover(function () {  //hover的时候有两个函数,一个是悬浮的时候 ,一个是离开悬浮的时候
      clearInterval(clock);
    },function () {
      clock = setInterval(Go_right,2000);
    })
    
    //给左右按钮加上 轮播 
    $(".right").click(Go_right);//你一秒走一次go_right函数,和我按一次走一次有区别吗?而且悬浮的时候i的固定住了
    $(".left").click(go_left);

    function go_left() {
        if (i == 0){ //因为索引是从0开始的
           i=img_num;
        }
        i--;
        $(".num li").eq(i).addClass("active").siblings().removeClass("active");
        $(".img li").eq(i).stop().fadeIn().siblings().stop().fadeOut();
    }
</script>

</body>
</html>
View Code

 

posted @ 2018-04-08 13:56  你是我的神奇  阅读(222)  评论(0编辑  收藏  举报