python之路[16] - DOM和jQuery

DOM

      文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口。它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。我们最为关心的是,DOM把网页和脚本以及其他的编程语言联系了起来。DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容。

查找元素

1、直接查找

document.getElementById             根据ID获取一个标签
document.getElementsByName          根据name属性获取标签集合
document.getElementsByClassName     根据class属性获取标签集合
document.getElementsByTagName       根据标签名获取标签集合

2、间接查找

parentNode          // 父节点
childNodes          // 所有子节点
firstChild          // 第一个子节点
lastChild           // 最后一个子节点
nextSibling         // 下一个兄弟节点
previousSibling     // 上一个兄弟节点
  
parentElement           // 父节点标签元素
children                // 所有子标签
firstElementChild       // 第一个子标签元素
lastElementChild        // 最后一个子标签元素
nextElementtSibling     // 下一个兄弟标签元素
previousElementSibling  // 上一个兄弟标签元素

节点与标签的区别:     节点会把标签中文本也找出来!  

  

操作

1、内容 

innerText   文本   
outerText
innerHTML   HTML内容
outerHTML
value       值 => 文本框,下来框 表单标签的值
 
获取 与 赋值:(其他同理)
text = obj.innerText   =>  获取包含的文本
obj.innerText = '123'

  

2、属性

attributes                // 获取所有标签属性  => 字典形式
setAttribute(key,value)   // 设置标签属性
getAttribute(key)         // 获取指定标签属性   => 没有的为null
  
/*
var atr = document.createAttribute("class");
atr.nodeValue="democlass";
document.getElementById('n1').setAttributeNode(atr);
*/

3、class操作

className                // 获取所有类名 => 字符串形式
classList.remove(cls)    // 删除指定类   => 列表形式
classList.add(cls)       // 添加类
<!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' onclick="Show(this)">价格趋势</li>
                    <li  target='d2'  onclick="Show(this)">市场分布</li>
                    <li  target='d3'  onclick="Show(this)">其他</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 type="text/javascript">
            function Show(obj){
                var target = obj.getAttribute('target');
                var menu = obj.parentElement.children;
                for(var i=0;i<menu.length;i++){
                    if(menu[i] == obj){
                        obj.className='active';
                    }else{
                        menu[i].removeAttribute('class');
                    }
                }
                //操作内容
                var con_node = document.getElementById('content');
                con = con_node.children;
                for(var j=0;j<con.length;j++){
                    var attr = con[j].getAttribute('con');
                    if(attr == target){
                        con[j].classList.remove('dis-con');
                    }else{
                        con[j].classList.add('dis-con');
                    }
                }
            }
            
            
        </script>
    </body>
</html>

demo

  

4、标签操作  

a.创建标签 

// 方式一
var tag = document.createElement('a')
tag.innerText = "alex"
tag.className = "c1"
tag.href = "http://www.cnblogs.com/5poi"
  
// 方式二
var tag = "<a class='c1' href='http://www.cnblogs.com/5poi'>5poi</a>"

  

 b.操作标签

// 方式一
var obj = "<input type='text' />";
xxx.insertAdjacentHTML("beforeEnd",obj);
xxx.insertAdjacentElement('afterBegin',document.createElement('p'))
  
//注意:第一个参数只能是'beforeBegin'、 'afterBegin'、 'beforeEnd'、 'afterEnd'
                        外部上边         内部顶部       内部最后      外部下边
 
// 方式二
var tag = document.createElement('a')
xxx.appendChild(tag)    # 追加
xxx.insertBefore(tag,xxx[1])   # 指定在xxx[1]前面插入
 
//移动
obj.appendChild(div)
//克隆
obj.cloneNode(true)  true => 表示克隆里面全部东西  默认:false只克隆标签

  

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <p> test 1:</p>
        <div>
            <input type="text" />
            <input type="button" value="提交"  onclick="Common(this)"/>
        </div>
        <div>
            <ul id="commonlist">
                <li>alex</li>
                <li>eric</li>
            </ul>
        </div>
        
        <p>test 2:</p>
        <div>
            <input type="text" />
            <input type="button" value="提交"  onclick="Common2(this)"/>
        </div>
        <div>
            <ul id="commonlist2">
                <li>alex</li>
                <li>eric</li>
            </ul>
        </div>
            
        
        <script type="text/javascript">
            function Common(obj){
                var val = obj.previousElementSibling.value;
                obj.previousElementSibling.value ='' ;
                var commonlist = document.getElementById('commonlist');
                //形式一
                var str = '<li>'+val+'</li>';
                commonlist.insertAdjacentHTML('beforeEnd',str);
            }
            function Common2(obj){
                var val = obj.previousElementSibling.value;
                obj.previousElementSibling.value ='' ;
                var commonlist = document.getElementById('commonlist2');
                //形式二
                tag = document.createElement('li');
                tag.innerText = val;
//                commonlist.appendChild(tag);
//                commonlist.insertBefore(tag,commonlist.children[1]);
                
                var temp = document.createElement('a');
                temp.innerText = '百度';
                temp.href = 'http://www.baidu.com';
                tag.appendChild(temp);
                commonlist.appendChild(tag);
                
            }
            

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

demo

  

 5、样式操作

var obj = document.getElementById('i1')
  
obj.style.fontSize = "32px";
obj.style.backgroundColor = "red";
 
#注意转换:
background-color  =>  backgroundColor

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .input-black{
                color: black;
            }
            .input-gray{
                color: gray;
            }
            
        </style>
    </head>
    <body>
        <input type="text" placeholder="请输入内容" />
        <p>test 1:</p>
        
        <input type="text" class="input-gray" value="请输入内容" onfocus="In(this)" onblur="Out(this)"/>
        
        
        
        
        <script type="text/javascript">
            function In(obj){
                obj.className = 'input-black';
                var current = obj.value;
                if(current == '请输入内容'){
                    obj.value = '';
                }
            }
            function Out(obj){
                
                var current = obj.value;
                if(current == '请输入内容'  || current.trim().length == 0){
                    obj.value = '请输入内容';
                    obj.className = 'input-gray';
                }
            }
            
            
            
        </script>
    </body>
</html>

demo

  

6、位置操作 

特指整个窗口
document.documentElement
 
总文档高度(文档流)
document.documentElement.offsetHeight
   
当前文档占屏幕高度(视口高度)
document.documentElement.clientHeight
   
可见范围高度: (自身height+border+padding)
tag.offsetHeight
   
当前标签距离文档''顶部''高度(距离上级定位高度)
#如果当前标签,的父标签有position 的话 就是距离position高度
tag.offsetTop
 
 
父定位标签
tag.offsetParent
   
滚动条距离顶部高度 (滚动高度)
tag.scrollTop
  
 
/*
    clientHeight -> 可见区域:height + padding
    clientTop    -> border高度
    offsetHeight -> 可见区域:height + padding + border
    offsetTop    -> 上级定位标签的高度
    scrollHeight -> 全文高:height + padding
    scrollTop    -> 滚动高度
    特别的:
        document.documentElement代指文档根节点
*/

  

7、提交表单

document.geElementById('form').submit()

  

8、其他操作

console.log                 输出框
alert                       弹出框
confirm                     确认框
   
// URL和刷新
location.href               获取URL
location.href = "url"       重定向
location.reload()           重新加载
   
// 定时器
setInterval                 多次定时器
clearInterval               清除多次定时器
setTimeout                  单次定时器
clearTimeout                清除单次定时器
 
 
setInterval(function (){...} , 1000 )  每1秒执行一次这个函数

  

事件

 

 

对于事件需要注意的要点:

  • this

  • event

  • 事件链以及跳出

 

1.注册事件:
a. <div onxxxx=''>
b.document....on.... =function()
 
2.this     代指当前正在操作的标签
3.event    触发当前标签的事件内容
 
onkeydown='down(this,event)'
 
console.log(e.KeyCode)
 
4. 自定义事件>默认事件 (优先级)
 
如果想要阻止后面事件发生, 需要 return false;
<a href='#' onclick = 'return Func();' ></a>
 
如果Func返回false 后面事件不再执行!!!!  

  实例: 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .logo{
                background-color:red ;
                height: 60px;
                color:white;
                font-size: 60px;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="logo" class='logo'>欢迎莅临指导</div>
        
        <script type="text/javascript">
            
            setInterval(function f1(){
                
                var logo = document.getElementById('logo').innerText;
                var first_str = logo[0];
                var sub_str = logo.slice(1,logo.length);
                var new_str = sub_str + first_str;
                document.getElementById('logo').innerText = new_str;
                
            },800)
            

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

  

折叠菜单

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            ul{
                padding: 0;
                margin: 0;
            }
            .father{
                width: 200px;
                height: 500px;
                background-color: gray;
            }
            .hidetitle{
                display:none;
            }
            .title{
                background-color: red;
                cursor: pointer;
            }
            .context{
                background-color: aquamarine;
            }
        </style>
    </head>
    <body>
        <div class="father">
            <div class="item">
                <div class="title" onclick="Show(this)">菜单一</div>
                <div class="context">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
            
            <div class="item">
                <div class="title" onclick="Show(this)">菜单二</div>
                <div class="context hidetitle">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
        
            <div class="item">
                <div class="title" onclick="Show(this)">菜单三</div>
                <div class="context hidetitle">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
        
            <div class="item">
                <div class="title" onclick="Show(this)">菜单四</div>
                <div class="context hidetitle">
                    <ul>
                        <li>123</li>
                        <li>123</li>
                        <li>123</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <script type="text/javascript">
            function Show(obj){
                
                var pre_node = obj.parentElement;
                obj.nextElementSibling.classList.remove('hidetitle');
                
                var father = obj.parentElement.parentElement;
                var all_son = father.children;
                for(var i=0;i<all_son.length;i++){
                    if (all_son[i] != pre_node){
                        all_son[i].children[1].classList.add('hidetitle');
                    }
                }
            }
        </script>
        
    </body>
</html>

  

 

jQuery

jQuery简述

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

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

比如: 

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

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

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

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

var $variable = jQuery对象 

var variable = DOM对象

 

选择器和筛选器

选择器

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

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

基本筛选器
$('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")   //正在执行动画效果的元素

属性选择器
$("div[id]")
$('[id="div1"]')  
$("div[name!='new']")
$("div[name^='new']")
$("div[name&='new']")
$("div[name*='new']")
 
//复合:
$('["alex="sb"][id]')
$("div[id][name$='man']")

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


表单对象属性选择器
$(":enabled")        //匹配所有可用元素
$(":disabled")        //匹配所有不可用元素
$(":checked")        //匹配所有选中中元素
$(":selected")        //匹配所有选中的option元素

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


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

  

筛选器

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

查找
$("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>

  

实例 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 和 文档处理)  

属性操作

属性操作
$("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属性


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

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

  

CSS操作

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

位置
$('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()        //获取文档的高度

尺寸
$("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

  

文档处理

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

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

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

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

复制
$("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>

  

事件 

页面载入

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

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

  

事件处理

//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" )        //解绑一个事件

  

事件委派    3.0+版本已弃用

// 与bind 不同的是当事件发生时才去临时绑定。
$("p").delegate("click",function(){
  do something...
});
 
$("p").undelegate();       //p元素删除由 delegate() 方法添加的所有事件
$("p").undelegate("click")   //从p元素删除由 delegate() 方法添加的所有click事件

  

事件

$("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()     //用户离开页面时

  

event object 对象

$("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>

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

绑定在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!')  
});  

 

动画效果

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

$("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>

  

实例 回调函数  

<!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>

  

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

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

  

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

$("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>

  

实例 京东轮播图

<!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

  

对象访问

$.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

  

 

posted @ 2018-07-05 17:36  richardzgt  阅读(305)  评论(0编辑  收藏  举报