码迷,mamicode.com
首页 > Web开发 > 详细

JQuery知识点总结

时间:2017-08-16 18:16:35      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:lob   for   对话框   ast   eve   after   images   移动   demo   

 
二   寻找元素(重要的选择器和筛选器) 

2.1选择器

2.1.1 基本选择器

$("*")
$("#id")   
$(".class")  
$("element")  
$(".class,p,div")       //每一个选择器匹配到的元素合并后一起返回。

2.1.2 层级选择器

$(".outer div")            //匹配所有的后代元素
$("parent > child")        //匹配所有的子元素
$("prev + next")           //匹配所有紧接在 prev 元素后的 next 元素 
$("prev ~ siblings ")      //匹配 prev 元素之后的所有 siblings 元素(同级元素)

2.1.3 基本筛选器

$(‘li:first‘);    //获取第一个元素
$(‘li:last‘)      //最后一个元素

:not(selector)              //去除所有与给定选择器匹配的元素配的元素
$("input:not(:checked)")    //查找所有未选中的 input 元素

$("tr:even")     //索引为偶数的元素,从 0 开始
$("tr:odd")      //索引为奇数的元素,从 0 开始

$("tr:eq(1)")    //给定索引值的元素
$("tr:gt(0)")    //大于给定索引值的元素
$("tr:lt(2)")    //小于给定索引值的元素

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

2.1.4 属性选择器

$("div[id]")
$(‘[id="div1"]‘)   
$("div[name!=‘new‘]")
$("div[name^=‘new‘]")
$("div[name&=‘new‘]")
$("div[name*=‘new‘]")

//复合:
$(‘["alex="sb"][id]‘)
$("div[id][name$=‘man‘]")

2.1.5 表单选择器

$(":input")      //匹配所有 input, textarea, select 和 button 元素
$(":text")       //所有的单行文本框
$(":password")   //所有密码框
$(":radio")      //所有单选按钮
$(":checkbox")   //所有复选框
$(":submit")     //所有提交按钮
$(":reset")      //所有重置按钮
$(":button")     //所有button按钮
$(":file")       //所有文件域
 
$("input:checked")    //所有选中的元素
$("select option:selected")    //select中所有选中的option元素

2.1.6 表单对象属性选择器

$(":enabled")        //匹配所有可用元素
$(":disabled")        //匹配所有不可用元素
$(":checked")        //匹配所有选中中元素
$(":selected")        //匹配所有选中的option元素

2.1.7 内容选择器

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

2.1.8 可见性选择器  

$(":hidden")        //匹配所有不可见元素,或者type为hidden的元素
$(":visible")       //匹配所有的可见元素

2.2筛选器

2.2.1 过滤

$("p").eq(0)       //当前操作中第N个jQuery对象,类似索引
$(‘li‘).first()    //第一个元素
$(‘li‘).last()     //最后一个元素
$(this).hasClass("test")    //元素是否含有某个特定的类,返回布尔值
$(‘li‘).has(‘ul‘)  //包含特定后代的元素

2.2.2 查找

$("div").children()      //div中的每个子元素,第一层
$("div").find("span")    //div中的包含的所有span元素,子子孙孙

$("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()      //所有的同辈元素,不包括自己

实例 左侧菜单 

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
        <style>
            .menu{
                position: fixed;
                left: 0;
                top: 0;
                background-color: darkgray;
                width: 150px;
                height: 500px;
            }
            .menu .title{
                background-color: greenyellow;
                color: red;
                cursor: pointer;
            }
            .hide{
                display: none;
            }
            .option{
                background-color: wheat;
            }
        </style>
    <body>
        
        <div class="menu">
            <div class="item">
                <div class="title">菜单一</div>
                <div class="option">
                    <div>1111</div>
                    <div>1111</div>
                    <div>1111</div>
                </div>
            </div>
            
            <div class="item">
                <div class="title">菜单二</div>
                <div class="option hide">
                    <div>1111</div>
                    <div>1111</div>
                    <div>1111</div>
                </div>
            </div>
            
            <div class="item">
                <div class="title">菜单三</div>
                <div class="option hide">
                    <div>1111</div>
                    <div>1111</div>
                    <div>1111</div>
                </div>
            </div>
        </div>
        
        
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(.title).click(function(){
                $(this).siblings().removeClass("hide")
                $(this).parent().siblings().children(.option).addClass(hide)
            })
        </script>
    </body>
</html>
demo

实例 tab切换

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            ul{
                list-style: none;
                padding: 0;
                margin: 0;
            }
            .title{
                background: #DDDDDD;
            }
            .clearfix:after{
                display: block;
                content: ‘x‘;
                height: 0;
                visibility: hidden;
                clear: both;
            }
            ul li{
                background: blue;
                color: white;
                float: left;
                padding: 8px 10px;
            }
            .content{
                border: 1px solid #DDDDDD;
                min-height: 200px;
            }
            .active{
                background-color: white;
                color: #000000;
            }
            .dis-con{
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="tab-menu">
            <div class="title clearfix">
                <ul>
                    <li  class="active" target=‘d1‘>价格趋势</li>
                    <li  target=‘d2‘  >市场分布</li>
                    <li  target=‘d3‘  >其他</li>
                </ul>
            </div>
            
            <div class="content" id=‘content‘>
                <div con=‘d1‘>content1</div>
                <div class="dis-con" con=‘d2‘>content2</div>
                <div class="dis-con" con=‘d3‘>content3</div>
            </div>
        </div>
        
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(.title ul li).click(function(){
                $(this).addClass(active).siblings().removeClass(active);
                var att = $(this).attr(target)
                $("div[con="+att+"]").removeClass(dis-con).siblings().addClass(dis-con)
            })
        </script>
    </body>
</html>
demo
三   操作元素(属性 CSS 和 文档处理)  

3.1 属性操作

3.1.1 基本属性操作

$("div").attr("id");            //返回文档中所有div的id属性值
$("div").attr("id","4");            //设置所有div的id属性
$("div").attr({‘alex‘:‘sb‘})        //设置多个属性,字典形式
$("div").removeAttr("name");       //将文档中图像的src属性删除

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

3.1.2 CSS类操作

$("p").addClass("selected");      //为p元素加上 ‘selected‘ 类
$("p").removeClass("selected");    //从p元素中删除 ‘selected‘ 类
$("p").toggleClass("selected");    //如果存在就删除,否则就添加

3.1.3 HTML代码/本文/值

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

实例 编辑框正反选

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
        <button onclick=‘selectAll()‘>全选</button>
        <button onclick=‘cancel()‘>取消</button>
        <button onclick=‘reverse()‘>反选</button>
        <table border="1" width="100px">
            <thead>
                
            </thead>
            <tbody>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td>1111</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td>2222</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td>3333</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td>4444</td>
                </tr>
            </tbody>
        </table>
        
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            function selectAll(){
                $(":checkbox").prop(checked,true)
            }
            function cancel(){
                $(":checkbox").prop(checked,false)
            }
            function reverse(){
                $(":checkbox").each(function (){
                    if( $(this).prop(checked)){
                        $(this).prop(checked,false)
                    }else{
                        $(this).prop(checked,true)
                    }
                })
            }
        </script>
    </body>
</html>
demo

实例 模态对话框

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .shadow{
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0,0,0,.6);
                z-index: 10;
            }
            .infoedit{
                position: fixed;
                top: 50%;
                left: 50%;
                margin-left: -150px;
                margin-top: -150px;
                width: 300px;
                height: 300px;
                background-color: white;
                z-index: 20;
            }
            .hide{
                display: none;
            }
        </style>
        <script src="jquery-1.8.2.js"></script>
        <script>
            $(function(){
                $([target=edit]).click(function(){
                    $(.shadow,.infoedit).removeClass(hide);
                    
                    var server_info = $(this).prevAll();
                    server_info.each(function(k,v){
                        var text = $(this).text();
                        var target = $(this).attr(target);
                        $(#+target).val(text);
                    })
                })
                
                $(#cancelEdit).click(function(){
                    $(.infoedit :text).val(‘‘);
                    $(.shadow,.infoedit).addClass(hide);
                })
                
                $(#addInfo).click(function(){
                    $(.shadow,.infoedit).removeClass(hide);
                })
            })
        </script>
    </head>
    <body>
        <button id="addInfo">添加</button>
        <table border="1">
            <thead>
                <tr>
                    <th>服务器</th>
                    <th>ip地址</th>
                    <th>端口号</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td target=‘server‘>c1.com</td>
                    <td target=‘ip‘>10.1.1.1</td>
                    <td target=‘port‘>8881</td>
                    <td target=‘edit‘>编辑</td>
                </tr>
                <tr>
                    <td target=‘server‘>c2.com</td>
                    <td target=‘ip‘>10.1.1.2</td>
                    <td target=‘port‘>8882</td>
                    <td target=‘edit‘>编辑</td>
                </tr>
                <tr>
                    <td target=‘server‘>c3.com</td>
                    <td target=‘ip‘>10.1.1.3</td>
                    <td target=‘port‘>8883</td>
                    <td target=‘edit‘>编辑</td>
                </tr>
            </tbody>
        </table>
        
        <div class="shadow hide"></div>
        <div class="infoedit hide">
            <form action="" method="get">
                <p>服务器:
                    <input type="text" id=‘server‘ />
                </p>
                
                <p>ip地址:
                    <input type="text" id=‘ip‘ />
                </p>
                
                <p>端口号:
                    <input type="text" id=‘port‘ />
                </p>
                
                <input type="submit" value="提交" />
                <input type="button" value="取消" id=‘cancelEdit‘/>
            </form>
        </div>
    </body>
</html>
demo

3.2 CSS操作

3.2.1 样式

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

3.2.2 位置

$(‘p‘).offset()     //元素在当前视口的相对偏移,Object {top: 122, left: 260}
$(‘p‘).offset().top
$(‘p‘).offset().left
$("p").position()   //元素相对父元素的偏移,对可见元素有效,Object {top: 117, left: 250}

$(window).scrollTop()       //获取滚轮滑的高度
$(window).scrollLeft()      //获取滚轮滑的宽度
$(window).scrollTop(‘100‘)  //设置滚轮滑的高度为100

$(window).height()          //获取窗口的高度
$(document).height()        //获取文档的高度

3.2.3 尺寸

$("p").height();    //获取p元素的高度
$("p").width();     //获取p元素的宽度

$("p:first").innerHeight()    //获取第一个匹配元素内部区域高度(包括补白、不包括边框)
$("p:first").innerWidth()     //获取第一个匹配元素内部区域宽度(包括补白、不包括边框)

$("p:first").outerHeight()    //匹配元素外部高度(默认包括补白和边框)
$("p:first").outerWidth()     //匹配元素外部宽度(默认包括补白和边框)
$("p:first").outerHeight(true)    //为true时包括边距

实例 返回顶部

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .goTop{
                position: fixed;
                right: 10px;
                bottom: 10px;
                width: 40px;
                height: 40px;
                background-color: darkgray;
                text-align: center;
            }
            .hide{
                display: none;
            }
        </style>
        
    </head>
    <body>
        <div style="height: 1000px;"></div>
        
        <div class="goTop hide">返回顶部</div>
        
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            
            window.onscroll = function(){

                if( $(window).scrollTop() > 50 ){
                    $(".goTop").removeClass(hide)
                }else{
                    $(".goTop").addClass(hide)
                }
            }
            
            $(.goTop).click(function(){
                
                $(window).scrollTop(0)
            })
            
        </script>
    </body>
</html>
demo

缓慢返回顶部(带效果):

$(‘#backTop‘).bind(‘click‘,function(){
    $(‘html,body‘).animate( {scrollTop:0} );
});

注:html,body需一起使用。

实例 滚动菜单 

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        
        <style type="text/css">
            body{
                margin: 0;
                padding: 0;
            }
            .head{
                height: 50px;
                background-color: burlywood;
            }
            .menu{
                position: absolute;
                left: 0;
                background-color: ghostwhite;
                width:200px;
                height: 600px;
                float:left;
            }
            .menu-fix{
                position: fixed;
                top:10px;
            }
            .father{
                background-color: gray;
                position: absolute;
                left: 210px;
            }
            .item{
                width: 800px;
                height: 600px;
            }
            .title{
                text-align: center;
            }
            .active{
                background-color: cornflowerblue;
                color: darkgreen;
            }
        </style>
    </head>
    <body>
        <div class="head"></div>
        
        <div class="menu">
            <div class="title active" target=‘c1‘>第一张</div>
            <div class="title" target=‘c2‘>第二张</div>
            <div class="title" target=‘c3‘>第三张</div>
        </div>
        
        <div class="father">
            <div class="content">
                <div class="item" con=‘c1‘>第一章</div>
                <div class="item" con=‘c2‘>第二章</div>
                <div class="item" con=‘c3‘>第三章</div>
            </div>
        </div>
        
        <script src="jquery-1.8.2.js"></script>
        <script>
            window.onscroll = function(){

                var current = $(window).scrollTop()
                if(current > 50 ){
                    $(.menu).addClass(menu-fix)
                }
                else{
                    $(.menu).removeClass(menu-fix)
                }
                
                if( current + $(window).height() == $(document).height() ){
                    $(.menu).children(":last").addClass(active).siblings().removeClass(active);
                    return
                }
                
                $(.item).each(function(){

                    var item_top = $(this).offset().top;
                    var item_height = $(this).height();
                    var title = $(this).attr(con)
                    if ( current > item_top && current < item_height+item_top){
                        $(".title[target="+title+"]").addClass(active).siblings().removeClass(active)
                    }
                    
                })
                
            }
        </script>
        
    </body>
</html>
demo

3.3 文档处理

3.3.1 内部插入

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

3.3.2 外部插入

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

3.3.3 替换

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

3.3.4 删除

$("p").empty();     //删除匹配的元素集合中所有的子节点,不包括本身
$("p").remove();    //删除所有匹配的元素,包括本身
$("p").detach();    //删除所有匹配的元素(和remove()不同的是:所有绑定的事件、附加的数据会保留下来)

3.3.5 复制

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

实例 克隆方法的应用

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

</head>
<body>
            <div class="outer">
                <div class="condition">

                        <div class="icons" style="display:inline-block">
                            <a onclick="add(this);"><button>+</button></a>
                        </div>

                        <div class="input" style="display:inline-block">
                            <input type="checkbox">
                            <input type="text" value="alex">
                        </div>
                </div>
            </div>

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

            function add(self){
                var $duplicate = $(self).parent().parent().clone();
                $duplicate.find(a[onclick="add(this);"]).attr(onclick,"removed(this)").children("").text("-");
                $duplicate.appendTo($(self).parent().parent().parent());

            }
           function removed(self){

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

           }

    </script>
</body>
</html>
demo
四   事件 

4.1 页面载入

  当页面载入成功后再运行的函数事件  使用后可以在开头位置写入jq代码

$(document).ready(function(){
  do something...
});

//简写
$(function($) {
  do something...
});

4.2 事件处理

//bind 为每个匹配元素绑定事件处理函数,绑定多个用{}。     3.0+版本已弃用
$("p").bind("click", function(){
  alert( $(this).text() );
});
$(menuF).bind({
    "mouseover":function () {
     $(menuS).parent().removeClass("hide");
     },"mouseout":function () {
     $(menuS).parent().addClass("hide");
}
});         

$("p").click(function(){})  =  $("p").bind("click",function(){})     

$("p").one( "click", fun...)    //one 绑定一个一次性的事件处理函数
$("p").unbind( "click" )        //解绑一个事件

4.3 事件委派    3.0+版本已弃用

// 与bind 不同的是当事件发生时才去临时绑定。
$("p").delegate("click",function(){
  do something...
});

$("p").undelegate();       //p元素删除由 delegate() 方法添加的所有事件
$("p").undelegate("click")   //从p元素删除由 delegate() 方法添加的所有click事件

4.4 事件

$("p").click();      //单击事件
$("p").dblclick();    //双击事件
$("input[type=text]").focus()  //元素获得焦点时,触发 focus 事件
$("input[type=text]").blur()   //元素失去焦点时,触发 blur事件
$("button").mousedown()//当按下鼠标时触发事件
$("button").mouseup()  //元素上放松鼠标按钮时触发事件
$("p").mousemove()     //当鼠标指针在指定的元素中移动时触发事件
$("p").mouseover()     //当鼠标指针位于元素上方时触发事件
$("p").mouseout()     //当鼠标指针从元素上移开时触发事件
$(window).keydown()    //当键盘或按钮被按下时触发事件
$(window).keypress()   //当键盘或按钮被按下时触发事件,每输入一个字符都触发一次
$("input").keyup()     //当按钮被松开时触发事件
$(window).scroll()     //当用户滚动时触发事件
$(window).resize()     //当调整浏览器窗口的大小时触发事件
$("input[type=‘text‘]").change()    //当元素的值发生改变时触发事件
$("input").select()    //当input 元素中的文本被选择时触发事件
$("form").submit()     //当提交表单时触发事件
$(window).unload()     //用户离开页面时

4.5 event object 对象

所有的事件函数都可以传入event参数方便处理事件

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

(evnet object)属性方法:
event.pageX   //事件发生时,鼠标距离网页左上角的水平距离
event.pageY   //事件发生时,鼠标距离网页左上角的垂直距离
event.type   //事件的类型
event.which   //按下了哪一个键
event.data   //在事件对象上绑定数据,然后传入事件处理函数
event.target  //事件针对的网页元素
event.preventDefault()  //阻止事件的默认行为(比如点击链接,会自动打开新页面)
event.stopPropagation()  //停止事件向上层元素冒泡

实例 拖动面板

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .bar{
                width: 250px;
                height: 250px;
                border: 1px solid gray;
                position: absolute;
                left: 10px;
                right: 10px;
            }
            .bar .title{
                height: 30px;
                background-color: burlywood;
            }
        </style>
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(function(){
                $(#title).mouseover(function(){
                    $(this).css(cursor,move);
                }).mousedown(function(e){
                    var _event  = e || window.event;
                    var old_x = _event.clientX;
                    var old_y = _event.clientY;
                    
                    var box_x = $(this).parent().offset().left;
                    var box_y = $(this).parent().offset().top;
                    
                    $(this).bind(mousemove,function(e){
                        var _event  = e || window.event;
                        var new_x = _event.clientX;
                        var new_y = _event.clientY;
                        
                        var new_box_x = box_x + (new_x - old_x);
                        var new_box_y = box_y + (new_y - old_y);
                        $(this).parent().css(left,new_box_x+px);
                        $(this).parent().css(top,new_box_y+px);
                        
                    })
                }).mouseup(function(){
                    $(this).unbind(mousemove);
                })
            })
            
        </script>
    </head>
    <body>
        <div class="bar">
            <div class="title" id=‘title‘>标题</div>
            <div class="content">content</div>
        </div>
    </body>
</html>
demo

解决: 拖动面板鼠标移动过快,移动断开问题

绑定在div上 鼠标移出div层 事件就消失了,绑定在 document 上也就是整个页面都有这个事件!

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .bar{
                width: 250px;
                height: 250px;
                border: 1px solid gray;
                position: absolute;
                left: 10px;
                right: 10px;
            }
            .bar .title{
                height: 50px;
                text-align: center;
                border: 1px solid red;
                background-color: burlywood;
                cursor: move;
            }
        </style>
        
    </head>
    <body>

        <div class="bar hide">
            <div class="title" id=‘title‘>标题</div>
            <div class="content">content</div>
        </div>
        
        
        <script src="jquery-2.1.4.min.js"></script>
        <script type="text/javascript">
            $(function(){
                
                var MFloat = false;
                var old_x,old_y;
                var box_x,box_y;
                
                $(.title).on(mousedown,function(e){
                    
                    var _event  = e || window.event;
                    
                    old_x = _event.clientX;
                    old_y = _event.clientY;
                    
                    box_x = $(.title).parent().offset().left;
                    box_y = $(.title).parent().offset().top;
                    MFloat = true;
                })
                
                $(document).mouseover(function(e){
                    if(MFloat){
                        var _event  = e || window.event;
                        var new_x = _event.clientX;
                        var new_y = _event.clientY;
                        
                        var new_box_x = box_x + (new_x - old_x);
                        var new_box_y = box_y + (new_y - old_y);
                        $(.title).parent().css(left,new_box_x+px);
                        $(.title).parent().css(top,new_box_y+px);
                    }
                }).mouseup(function(){
                    MFloat = false;
                })
            })
            
        </script>
    </body>
</html>
demo

event.clientX、event.clientY

鼠标相对于浏览器窗口可视区域的X,Y坐标(窗口坐标),可视区域不包括工具栏和滚动条。IE事件和标准事件都定义了这2个属性

event.pageX、event.pageY

类似于event.clientX、event.clientY,但它们使用的是文档坐标而非窗口坐标。这2个属性不是标准属性,但得到了广泛支持。IE事件中没有这2个属性。

event.offsetX、event.offsetY

鼠标相对于事件源元素(srcElement)的X,Y坐标,只有IE事件有这2个属性,标准事件没有对应的属性。

event.screenX、event.screenY

鼠标相对于用户显示器屏幕左上角的X,Y坐标。标准事件和IE事件都定义了这2个属性

技术分享

input 输入框的change事件,要在input失去焦点的时候才会触发!

$(‘input[name=myInput]‘).change(function() { ... });

在输入框内容变化的时候不会触发change,当鼠标在其他地方点一下才会触发

用下面的方法会生效,input

$("#input_id").on(‘input‘,function(e){  
   alert(‘Changed!‘)  
});  
五 动画效果

5.1 基本  在动画完成后,可选地触发一个回调函数!

$("p").show()        //显示隐藏的匹配元素
$("p").show("slow");    //参数表示速度,("slow","normal","fast"),也可为900毫秒
$("p").hide()        //隐藏显示的元素
$("p").toggle();      //切换 显示/隐藏
$("p").stop()              //停止所有在指定元素上正在运行的动画。

实例 显示与隐藏

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style></style>
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(function(){
                $(#hide).click(function(){
                    $(p).hide(1000);
                })
                $(#show).click(function(){
                    $(p).show(1000);
                })
                $(#toggle).click(function(){
                    $(p).toggle(1000);
                })
            })
        </script>
    </head>
    <body>
        <p style="background-color: pink;">hello</p>
        <button id="hide">隐藏</button>
        <button id="show">显示</button>
        <button id="toggle">隐藏/显示</button>
    </body>
</html>
demo

实例 回调函数

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style></style>
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(function(){
                $(#hide).click(function(){
                    $(p).hide(1000,function(){
                        alert(1);
                    });
                })
                $(#show).click(function(){
                    $(p).show(1000);
                })
                $(#toggle).click(function(){
                    $(p).toggle(1000);
                })
            })
        </script>
    </head>
    <body>
        <p style="background-color: pink;">hello</p>
        <button id="hide">隐藏</button>
        <button id="show">显示</button>
        <button id="toggle">隐藏/显示</button>
    </body>
</html>
demo

5.2 淡入淡出  在动画完成后,可选地触发一个回调函数!

$("p").fadeIn("900");        //用900毫秒时间将段落淡入
$("p").fadeOut("900");       //用900毫秒时间将段落淡出
$("p").fadeToggle("900");     //用900毫秒时间将段落淡入,淡出
$("p").fadeTo("slow", 0.6);    //用900毫秒时间将段落的透明度调整到0.6

实例 淡入淡出

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(function(){
                $(#in).click(function(){
                    $(#id1).fadeIn(1000);
                    $(#id2).fadeIn(1000);
                    $(#id3).fadeIn(1000);
                });
                $(#out).click(function(){
                    $(#id1).fadeOut(1000);
                    $(#id2).fadeOut(1000);
                    $(#id3).fadeOut(1000);
                });
                $(#toggle).click(function(){
                    $(#id1).fadeToggle(1000);
                    $(#id2).fadeToggle(1000);
                    $(#id3).fadeToggle(1000);
                });
                $(#fadeto).click(function(){
                    $(#id1).fadeTo("slow", 0.6);
                    $(#id2).fadeTo("fast", 0.4);
                    $(#id3).fadeTo("slow", 0.2);
                });
                
            })
        </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="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>
        
    </body>
</html>
demo

5.3 滑动  在动画完成后,可选地触发一个回调函数!

$("p").slideDown("900");    //用900毫秒时间将段落滑下
$("p").slideUp("900");     //用900毫秒时间将段落滑上
$("p").slideToggle("900");  //用900毫秒时间将段落滑上,滑下

实例 滑动

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
        #flipshow,#content,#fliphide,#toggle{
            padding: 5px;
            text-align: center;
            background-color: #ddd;
            border:solid 1px red;
        }
        #content{
            padding: 50px;
            display: none;
        }
        </style>
        <script src="jquery-1.8.2.js"></script>
        <script>
            $(function(){
                 $("#flipshow").click(function(){
                     $("#content").slideDown(1000);
                 });
                  $("#fliphide").click(function(){
                     $("#content").slideUp(1000);
                 });
                  $("#toggle").click(function(){
                     $("#content").slideToggle(1000);
                 })
            })
            
        </script>
    </head>
    <body>
        <div id="flipshow">出现</div>
        <div id="fliphide">隐藏</div>
        <div id="toggle">toggle</div>
    
        <div id="content">helloworld</div>
    </body>
</html>
demo

实例 京东轮播图

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            body{
                margin: 0;
            }
            ul{
                padding: 0;
                margin: 0;
            }
            ul li{
                list-style: none;
                padding: 0;
            }
            .outer{
                width:790px ;
                height: 340px;
                margin: 0 auto;
                border: darkturquoise dashed 6px;
                position: relative;
                cursor: pointer;
            }
            .outer:hover .btn{
                display: block;
            }
            .outer .img ul li img{
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
            }
            .outer .b-slider{
                position: absolute;
                bottom: 20px;
                left: 50%;
                margin-left: -10%;
                cursor:default;
            }
            .outer .b-slider .num{
                text-align: center;
                border-radius: 25px;
                font-size: 0;
                background-color: hsla(0,0%,100%,.3);
                height: 20px;
            }            
            .outer .b-slider .num li{
                display: inline-block;
                width: 12px;
                height: 12px;
                border-radius: 100%;
                background-color: white;
                text-align: center;
                margin: 4px 5px;
            }
            .outer .b-slider .num li.active{
                background-color: #db192a;
            }
            .btn{
                position: absolute;
                top: 50%;
                margin-top: -30px;
                width: 30px;
                height: 60px;
                background: rgba(0,0,0,.1);
                text-align: center;
                line-height: 60px;
                color: white;
                font-weight: bolder;
                display: none;
                cursor: pointer;
            }
            .btn:hover{
                background: rgba(0,0,0,.6);
            }
            .outer .right{
                right: 0;
            }
            
        </style>
        <script src="jquery-2.2.3.min.js"></script>
        <script type="text/javascript">
            $(function(){
                
                //生成底部标签:
                var size = $(.img img).size();
                for (var i= 1;i<=size;i++){
                    $(.b-slider .num).append(<li></li>);
                }
                
                $(.num li).first().addClass(active);
                $(.img li).first().show().siblings().hide();
                
                $(.num li).mouseover(function(){
                    $(this).addClass(active).siblings().removeClass(active);
                    var index = $(this).index();
                    i = index;
                    $(.img li).eq(index).stop().fadeIn(500).siblings().stop().fadeOut(500);
                })
                
                var time = setInterval(move,3000);
                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(500).siblings().stop().fadeOut(500);
                }
                
                $(.outer).hover(function(){
                    clearInterval(time);
                },function(){
                    time = setInterval(move,3000);
                });
                
                $(.right).click(function(){
                    move();
                })
                $(.left).click(function(){
                    if(i==0){i=size}
                    i=i-2;
                    move();
                })
                
            })

        </script>
    </head>
    <body>
        <div class="outer">
            
            <div class="img">
                <ul>
                    <li><a href="#"><img src="1.jpg" /></a></li>
                    <li><a href="#"><img src="2.jpg" /></a></li>
                    <li><a href="#"><img src="3.jpg" /></a></li>
                    <li><a href="#"><img src="4.jpg" /></a></li>
                    <li><a href="#"><img src="5.jpg" /></a></li>
                    <li><a href="#"><img src="6.jpg" /></a></li>
                    <li><a href="#"><img src="7.jpg" /></a></li>
                    <li><a href="#"><img src="8.jpg" /></a></li>
                </ul>
            </div>
            
            <div class="b-slider">
                <ul class="num"></ul>
            </div>
            
            <div class="btn left"> < </div>
            <div class="btn right"> > </div>
            
        </div>
    </body>
</html>
demo

实例 放大镜

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            .outer{
                position: relative;
            }
            .imgshow{
                width: 430px;
                height: 430px;
                border: 5px cornflowerblue dashed;
                position: relative;
                overflow: hidden;
            }
            .imgzoom{
                position: absolute;
                left: 0;
                top: 0;
                width: 170px;
                height: 170px;
                background-color: gray;
                opacity: 0.6;
                display: none;
            }
            .bigshow{
                border: 5px darkgreen solid;
                position: absolute;
                left: 440px;
                top: 0;
                width: 500px;
                height: 500px;
                overflow: hidden;
                display: none;
            }
            .bigshow img{
                position: absolute;
            }
        </style>
    </head>
    <body>
        <div class="outer">
            <div class="imgshow">
                <div class="imgzoom"></div>
                <img src="small.jpg" alt="" />
            </div>
            <div class="bigshow">
                <img src="big.jpg" alt="" />
            </div>
        </div>
        
        
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(function(){
                
                $(.imgshow).bind(mouseover,function(){
                    $(.imgzoom).css(display,block);
                    $(.bigshow).css(display,block);
                });
                $(.imgshow).bind(mouseout,function(){
                    $(.imgzoom).css(display,none);
                    $(.bigshow).css(display,none);
                });
                
                $(.imgshow).bind(mousemove,function(e){
                    
                    var _event = e || window.event;
                    
                    var small_box_height = $(.imgshow).height();
                    var small_box_width = $(.imgshow).width();
                    
                    var zoom_height = $(.imgzoom).height();
                    var zoom_width = $(.imgzoom).width();
                    
                    var zoom_height_half = $(.imgzoom).height()/2 ;
                    var zoom_width_half = $(.imgzoom).width()/2 ;
                    
                    var mouse_left = _event.clientX;
                    var mouse_top = _event.clientY;
                    
                    var zoom_move_left = mouse_left - zoom_width_half;
                    var zoom_move_top = mouse_top - zoom_height_half;
                    
                    if(zoom_move_left < 0 ){
                        zoom_move_left = 0 ;
                    }else if(zoom_move_left > small_box_width - zoom_width){
                        zoom_move_left = small_box_width - zoom_width;
                    }
                    
                    if(mouse_top < zoom_height_half ){
                        zoom_move_top = 0 ;
                    }else if(zoom_move_top > small_box_height - zoom_height){
                        zoom_move_top = small_box_height - zoom_height ;
                    }
                    
                    $(.imgzoom).css(left,zoom_move_left+px);
                    $(.imgzoom).css(top,zoom_move_top+px);
                    
                    var percentX = ( $(.bigshow img).width() - $(.bigshow).width() )/ (small_box_width - zoom_width)
                    var percentY = ( $(.bigshow img).height() - $(.bigshow).height() )/ (small_box_height - zoom_height)
                    
                    $(.bigshow img).css(left , -percentX*zoom_move_left+px);
                    $(.bigshow img).css(top , -percentY*zoom_move_top+px);
                })
                
            })
        </script>
    </body> 
</html>
demo

实例 编辑框

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .outer{
                height: 50px;
            }
            .editMod{
                padding: 10px;
                background-color: gray;
                text-decoration: none;
                color: white;
            }
            .editing{
                background-color: wheat;
                color: red;
            }
        </style>
    </head>
    <body>
        <div class="outer">
            <button id="selectAll" onclick="selectAll(‘#editMod‘,‘#tb1‘);">全选</button>
            <button id="reserve" onclick="reserve(‘#editMod‘,‘#tb1‘);">反选</button>
            <button id="cancelAll" onclick="cancelAll(‘#editMod‘,‘#tb1‘);">取消</button>
            <a href="javascript:void(0)" class="editMod" id="editMod" onclick="editing(this,‘#tb1‘);">进入编辑模式</a>
        </div>    
        
            <table border="1">
                <thead>
                    <tr>
                        <th>选择</th>
                        <th>主机名</th>
                        <th>端口</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody id="tb1">
                    <tr>
                        <td><input type="checkbox" /></td>
                        <td edit=‘true‘>v1</td>
                        <td>v11</td>
                        <td edit=‘true‘ edit-type=‘select‘ select-value=‘1‘ global-key=‘STATUS‘  select-text=‘在线‘>在线</td>
                    </tr>
                    <tr>
                        <td><input type="checkbox" /></td>
                        <td  edit=‘true‘>v2</td>
                        <td>v22</td>
                        <td edit=‘true‘ edit-type=‘select‘ select-value=‘2‘ global-key=‘STATUS‘ select-text=‘下线‘>下线</td>
                    </tr>
                    <tr>
                        <td><input type="checkbox" /></td>
                        <td  edit=‘true‘>v3</td>
                        <td>v33</td>
                        <td edit=‘true‘ edit-type=‘select‘ select-value=‘1‘ global-key=‘STATUS‘ select-text=‘在线‘>在线</td>
                    </tr>
                </tbody>
            </table>
            
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            STATUS = [
                {id:1 , value:在线},
                {id:2 , value:下线},
            ]
            $(function(){
                bindCheckbox(#editMod,#tb1);
                
            })
            
            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;
                }
            }
            
            function MulKeySelect(self){
                if(window.globalCtrlKeyPress){
                    var index = $(self).parent().index();
                    var value = $(self).val();
                    $(self).parent().parent().nextAll().find("td input[type=‘checkbox‘]:checked").each(function(){
                        $(this).parent().parent().children().eq(index).children().val(value);
                    })
                }
            }
            
            function bindCheckbox(mode,tb){
                $(tb).find(:checkbox).bind(click,function(){
                    var $tr = $(this).parent().parent();
                    if( $(mode).hasClass(editing) ){
                        if( $(this).prop(checked)){
                            RowIntoEdit($tr);
                        }else{
                            RowOutEdit($tr);
                        }
                    }
                })
            }
            
            function selectAll(mode,tb){
                if( $(mode).hasClass(editing) ){
                    
                    $(tb).children().each(function(){
                        var tr = $(this);
                        var check = tr.children().find(:checkbox);
                        if(check.prop(checked)){
                            
                        }else{
                            check.prop(checked,true);
                            RowIntoEdit(tr);
                        }
                    })
                }else{
                    $(tb).find(:checkbox).prop(checked,true);
                }
            }
            function reserve(mode,tb){
                if( $(#editMod).hasClass(editing) ){
                    
                    $(tb).children().each(function(){
                        var tr = $(this);
                        var check = tr.children().first().find(:checkbox);
                        if(check.prop(checked)){
                            check.prop(checked,false);
                            RowOutEdit(tr);
                        }else{
                            check.prop(checked,true);
                            RowIntoEdit(tr);
                        }
                    })
                    
                }else{
                    $(tb).children().each(function(){
                        if($(this).find(:checkbox).prop(checked)){
                            $(this).find(:checkbox).prop(checked,false);
                        }else{
                            $(this).find(:checkbox).prop(checked,true);
                        }
                    })
                    
                }
            }
            function cancelAll(mode,tb){
                if( $(mode).hasClass(editing) ){
                    
                    $(tb).children().each(function(){
                        var tr = $(this);
                        var check = tr.children().find(:checked);
                        if(check.prop(checked)){
                            check.prop(checked,false);
                            RowOutEdit(tr);
                        }else{
                            
                        }
                    })
                }else{
                    $(tb).find(:checkbox).prop(checked,false);
                }
            }
            function editing(self,tb){
                if( $(self).hasClass(editing) ){
                    $(self).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{
                    $(self).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{
                            
                        }
                    });
                }    
            }
            
            function RowIntoEdit(tr){
                tr.children().each(function(){
                    var td = $(this);
                    var edit_check = td.attr(edit);
                    if(edit_check == true ){
                        var edit_type = td.attr(edit-type);
                        if(edit_type == select){
                            
                            var select_value = td.attr(select-value);
                            var global_key = td.attr(global-key);
                            var select_attr = { onchange : MulKeySelect(this);};
                            var select_css = "";
                            var temp = createSelect(attr=select_attr,css=select_css,option_dict=global_key,current_value=select_value);
                            td.html(temp);
                            
                        }else{
                            var text = td.text();
                            var temp = "<input type=‘text‘ value=‘"+text+"‘/>"
                            td.html(temp);
                        }
                    }
                })
            }
            function RowOutEdit(tr){
                tr.children().each(function(){
                    var td = $(this);
                    var edit_check = td.attr(edit);
                    if(edit_check == true ){
                        var edit_type = td.attr(edit-type);
                        if(edit_type == select){
                            
                            var select_val = td.children(:first).val();
                            var select_text = td.children(:first).find("option[select_value=‘"+select_val+"‘]").text();
                            td.attr(select-value,select_val);
                            td.attr(select-text,select_text);
                            td.text(select_text);
                            
                        }else{
                            var text = td.children().first().val();
                            td.text(text);
                        }
                    }
                    
                })
            }
            function createSelect(attr,css,option_dict,current_value){

                var sel = document.createElement(select);
                
                $.each(attr, function(k,v) {
                    $(sel).attr(k,v);
                });
                $.each(css, function(k,v) {
                    $(sel).css(k,v);
                });
                
                //生成下拉选项:
                $.each(window[option_dict], function(k,v) {
                    var select_num = v[id];
                    var select_value = v[value];
                    var opp = document.createElement(option);
                    
                    if(current_value == select_num){  //默认值相同应该选中
                        $(opp).attr(select_value,select_num).attr(select-text,select_value).text(select_value).val(select_num).attr(selected,true).appendTo($(sel));
                    }else{
                        $(opp).attr(select_value,select_num).attr(select-text,select_value).text(select_value).val(select_num).appendTo($(sel));
                    }

                });
                
                return sel;
            }
            
        </script>
        
    </body>
</html>
demo
六 对象访问
$.trim()   //去除字符串两端的空格
$.each()   //遍历一个数组或对象,for循环
$.inArray() //返回一个值在数组中的索引位置,不存在返回-1  
$.grep()   //返回数组中符合某种标准的元素
$.extend()  //将多个对象,合并到第一个对象
$.makeArray() //将对象转化为数组
$.type()    //判断对象的类别(函数对象、日期对象、数组对象、正则对象等等
$.isArray() //判断某个参数是否为数组
$.isEmptyObject() //判断某个对象是否为空(不含有任何属性)
$.isFunction()    //判断某个参数是否为函数
$.isPlainObject() //判断某个参数是否为用"{}"或"new Object"建立的对象
$.support()       //判断浏览器是否支持某个特性

循环:json对象:

$.each( data, function(k,v){ .... } )

return false  =>  break
return true  =>  continue

判断空object对象:

function isEmptyObject(e) {
    var t;
    for(t in e)
        return !1;
    return !0;
}
七 插件扩展机制
//方式一    jQuery 可以简写成 $
jQuery.fn.extend({
    hello:function(){
        return $(this).text();
    }
});

var index = $(‘.title‘).hello()
alert(index);


<div class="title">1111</div>
<div class="title">2222</div>
//方式二
$.extend({
    hello1 :function(arg){
        var index = $(arg).text();
        return index;
    }
})

var index = $.hello1(‘.title‘)
alert(index)


<div class="title">1111</div>
<div class="title">2222</div>

实例

技术分享
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="jquery-1.8.2.js"></script>
        <script type="text/javascript">
            $(function(){
                //方式一:
                $.fn.extend({
                    hello:function(){
                        return $(this).text();
                    }
                });
                
                //方式二:
                $.extend({
                    hello1 :function(arg){
                        var index = $(arg).text();
                        return index;
                    }
                })
                
                //方式一:
//                var index = $(‘.title‘).hello()
//                alert(index);
                
                //方式二:
                var index = $.hello1(‘.title‘)
                alert(index)
            })
        </script>
    </head>
    <body>
        <div class="title">1111</div>
        <div class="title">2222</div>
    </body>
</html>
demo
八 补充

1.input 事件, 输入时触发:

$(#inp).on(input,function(){});

2.文件上传input  变更时触发:

$(".upload").on("change","input[type=‘file‘]",function(){
    ...
});

3.ajax异步请求页面时,必须返回数据,不能在后台指定跳转页面

4.判断是否存在该标签:

$(xxx).length > 0

5.DOM对象、JQ对象 转换

获取 Dom对象
document.getElementsTagName(‘div‘)[0]

获取 JQuery对象
$(‘div‘).first()

Dom对象  =>  JQuery对象
$(document.getElementsTagName(‘div‘)[0])

JQuery对象  =>  Dom对象
$(‘div‘).first()[0]

6.JSON 转换

JSON.parse(arg)       字符串=>原型
JSON.stringify(arg)   原型=>字符串

 

JQuery知识点总结

标签:lob   for   对话框   ast   eve   after   images   移动   demo   

原文地址:http://www.cnblogs.com/ArmoredTitan/p/7374574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!