zoukankan      html  css  js  c++  java
  • 原生js dom记忆的内容

     0001:原生的ajax的封装

     0002:事件代理。

     0003:

    1.DOM基础
    getElementById
    getElementByTagName
    getElementByName

    getElementsByClass

    querySelector

    querySelectorAll
    getAttribute
    setAttribute
    removeAttribute

    domobj.tagName
    domobj.innerHTML

    innerHTML与innerText的区别。http://akunamotata.iteye.com/blog/440863
    domobj.id
    domobj.title
    domobj.style
    domobj.className
    document.getElementsByTagName('li')[0]
    document.getElementsByTagName('li')[0].value
    document.getElementsByTagName('li')[0].checked
    document.getElementsByName('add')[0].value
    下面两种获取属性的方法相同:
    document.getElementById('box').getAttribute('mydiv')

    ==============================================

    属性 :

    childeNodes

    innerHTML

    style

    firstChild    返回第一个子节点
    lastChild     
    返回最后一个子节点
    parentNode   返回父节点的对象。
    nextSibling   
    返回下一个兄弟节点的对象
    previousSibling 返回前一个兄弟节点的对象
    nodeName 
    返回节点的HTML标记名称,使用英文的大写字母,如P, FONT

    ==============================================

    原生操作dom的方法。

    appendChild(node) 
    removeChild(childreference)
    cloneNode(deepBoolean) 但是id属性会被修改
    insertBefore(newElment,targetElement) 当前节点前插入新的节点

    ==============================================


    2.层级节点属性
    childNodes

    原生js中常用的方法,内置对象,机制
    1.js遍历数组和对象。用for遍历数组用for in 遍历对象。
    2. foreach在原生的js中Array并没有这个方法,需要去模仿,本质太过复杂,自己去网页上看吧(本地);
    3. document.a.b.value;
    <script>
    function test()
    {
    if(document.a.b.value.length>50)
    {
    alert("不能超过50个字符!");
    document.a.b.focus();
    return false;
    }
    }
    </script>
    <form name=a onsubmit="return test()">
    <textarea name="b" cols="40" wrap="VIRTUAL" rows="6"></textarea>
    <input type="submit" name="Submit" value="check">
    </form>
    4. DOM2下addEventListener attachEvent的区别。
    -----------------------------------------------------------------------

    addEventListener与attachEvent的区别(之所以用他的原因1.绑定位置元素。2.可以解绑。3.可以绑定多个元素)
    1. 支持的浏览器

        addEventListener在支持DOM2的浏览器中使用,如FF, Chrome等

        attachEvent为IE所用
    2. 处理程序执行阶段

        addEventListener的第三个参数为true时,在捕获阶段执行,为false时,在冒泡阶段执行

        attachEvent的均在冒泡阶段执行
    3. 作用域

        addEventListener的作用域为元素作用域,this为element的引用

        addEvent的为全局作用域,this为window的引用
    4. 事件处理程序执行顺序

        addEventHander:执行顺序与添加顺序一致

        attachEvent:执行顺序与添加顺序相反
    5. element.removeEventListener(type, handler, phase);

          参数必须与addEventListener的参数一样。注意:handler不可以是匿名函数
    6.3.5 移除事件处理程序

          element.detachEvent(type, handler);

          参数必须与attachEvent的参数一样。注意:handler不可以是匿名函数
    js也可以触发自定义事件,但是我们不知道何用。
    ------------------------------------------------------------------
    5. 通过对三个函数的分析,我们可以知道:escape()除了 ASCII 字母、数字和特定的符号外,对传进来的字符串全部进行转义编码,因此如果想对URL编码,最好不要使用此方法。而encodeURI() 用于编码整个URI,因为URI中的合法字符都不会被编码转换。encodeURIComponent方法在编码单个URIComponent(指请求参 数)应当是最常用的,它可以讲参数中的中文、特殊字符进行转义,而不会影响整个URL。
    6. __proto__ prototype 方法

    a.所有构造器/函数的__proto__都指向Function.prototype,它是一个空函数(Empty function)
    b. Function.prototype也是唯一一个typeof XXX.prototype为 “function”的prototype。其它的构造器的prototype都是一个对象。如下
    c. console.log(Function.prototype.__proto__ === Object.prototype) // true
    d.所有对象的__proto__都指向其构造器的prototype
    e.可以看到p.__proto__与Person.prototype,p.constructor.prototype都是恒等的,即都指向同一个对象。
    f.建议用我们所说的Person.prototype.run={}而不推荐用Person.prototype={},后边这样子写会覆盖默认的继承的属性和方法。
    7.js创建二维数组。
    a、 创建二维数组方法一:先创建一个一维数组,然后该一维数组的所有成员再创建一维数据

    var persons = new Array();


    persons[0] = new Array();
    persons[1] = new Array();
    persons[2] = new Array();


    persons[0][0] = "zhangsan";
    persons[0][1] = 25;
    persons[1][0] = "lisi";
    persons[1][1] = 22;
    b.var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32]];
    多维数组的length属性返回的是多维数组第一维的长度,而不是多维数组中元素的个数。
    8. 判断多维数组的长度,需要先判断是不是数组对象,然后判断长度,本地网页中有。
    //判断某个对象是不是数组
    function isArray(obj) {
    return obj && ( typeof obj === 'object') && (obj.constructor == Array);
    }
    9.分清克隆和继承的区别。
    10.function People(name)
    {
    this.name=name;
    //对象方法
    this.Introduce=function(){
    alert("My name is "+this.name);
    }
    }
    //类方法
    People.Run=function(){
    alert("I can run");
    }
    //原型方法
    People.prototype.IntroduceChinese=function(){
    alert("我的名字是"+this.name);
    }
    注意第二的类方法,如果放在function里边,类似闭包,也算是类方法。(自己理解)
    11.类的property方法,的property属性=new 出来的对象。
    function baseClass()
    {
    this.showMsg = function()
    {
    alert("baseClass::showMsg");
    }
    }

    function extendClass()
    {
    this.showMsg =function ()
    {
    alert("extendClass::showMsg");
    }
    }

    extendClass.prototype = new baseClass();
    var instance = new extendClass();

    instance.showMsg();//显示extendClass::showMsg
    12.
    trigger()绑定

    $(selector).trigger(event,eventObj,param1,param2,...)
    $(document).ready(function(){
      $("input").select(function(){
        $("input").after(" Text marked!");
      });
      $("button").click(function(){
        $("input").trigger("select");
      });
    });
    多个事件绑定同一个函数

    $(document).ready(function(){
    $("p").on("mouseover mouseout",function(){
    $("p").toggleClass("intro");
    });
    });
    多个事件绑定不同函数

    $(document).ready(function(){
    $("p").on({
    mouseover:function(){$("body").css("background-color","lightgray");},
    mouseout:function(){$("body").css("background-color","lightblue");},
    click:function(){$("body").css("background-color","yellow");}
    });
    });
    绑定自定义事件

    $(document).ready(function(){
    $("p").on("myOwnEvent", function(event, showName){
    $(this).text(showName + "! What a beautiful name!").show();
    });
    $("button").click(function(){
    $("p").trigger("myOwnEvent",["Anja"]);
    });
    });
    传递数据到函数

    function handlerName(event)
    {
    alert(event.data.msg);
    }

    $(document).ready(function(){
    $("p").on("click", {msg: "You just clicked me!"}, handlerName)
    });
    适用于未创建的元素

    $(document).ready(function(){
    $("div").on("click","p",function(){
    $(this).slideToggle();
    });
    $("button").click(function(){
    $("<p>This is a new paragraph.</p>").insertAfter("button");
    });
    });
    13.js获取元素的宽高。
    第一种情况就是宽高都写在样式表里,就比如#div1{120px;}。这中情况通过#div1.style.width拿不到宽度,而通过#div1.offsetWidth才可以获取到宽度。

    第二种情况就是宽和高是写在行内中,比如style="120px;",这中情况通过上述2个方法都能拿到宽度。

    小结,因为id.offsetWidth和id.offsetHeight无视样式写在样式表还是行内,所以我们获取元素宽和高的时候最好用这2个属性。注意如果不是写在行内style中的属性都不能通过id.style.atrr来获取。

    现 在的前端制作很少直接把样式写style里了,都是写在样式表里。如果你要获取的样式没有相对应的(就像#div1.style.width对 应#div1.offsetWidth),就只能分别针对不用浏览器来获取样式表的属性了,可以试着搜索“JS 获取样式属性”之类的。

    代码:
    var o = document.getElementById("view");
    var h = o.offsetHeight; //高度
    var w = o.offsetWidth; //宽度
    14. call方法的使用
    这个是flash调用我们js方法的时候用call方法。
    ExternalInterface.call("vjjFlash", "eventType");
    如果我们js直接调自己的js方法的话:
    15. call方法和apply方法的运用的区别。
    上面中人,如果后边传arguments的的话,就用apply,如果直接写了一个参数的话就用call。
    16. this和arguments是我们每个函数自带的隐藏属性。
    17.http://blog.sina.com.cn/s/blog_6f1f9ead0100n1f6.html
    18.
    var script = function(src, charset) {
    var s = document.createElement("script");
    s.charset = charset || 'utf-8';
    s.type = "text/javascript";
    s.async = true;
    s.src = src;
    document.getElementsByTagName("body")[0].appendChild(s);
    }
    script(videoPlusSrc);
    19.//$("img").get().reverse();
    20.  原生js表单控制:

    ====================================

    21.

    那如果点击一个li,想知道他的index 原生dom的方法 就是使用js闭包和立即执行匿名函数

    var targetNode = document.getElementById('list').getElementsByTagName('li');
        var i = 0;
        var targetLength = targetNode.length;
        for (i; i < targetLength; i++) {
            targetNode[i].onclick = (function(num) {
                return function() {
                        alert(num);
                }
            })(i);
        }

    =====================================================

    22.

    document方法:
    getElementById(id) 返回指定结点的引用
    getElementsByTagName(name) 返回文档中所有匹配的元素的集合
    createElement(name) 创建指定类型的新结点
    createTextNode(text) 创建一个纯文本结点
    element方法:
    getAttribute(id) 返回指定属性的值
    setAttribute(id,value) 给属性赋值
    removeAttribute(id) 移除指定属性和它的值
    getElementsByTagName(name) 返回结点内所有匹配的元素的集合
    node方法:
    appendChild(child) 给指定结点添加一个新的子结点
    removeChild(child) 移除指定结点的子结点
    replaceChild(newChild,oldChild) 替换指定结点的子结点
    insertBefore(newChild,refChild) 在同一层级的结点前面插入新结点
    hasChildNodes() 如果结点有子结点则返回true
    node属性:
    nodeName 以字符串的格式存放结点的名称
    nodeType 以整型数据格式存放结点的类型
    nodeValue 以可用的格式存放结点的值
    parentNode 指向结点的父结点的引用
    childNodes 指向子结点的引用的集合
    firstChild 指向子结点结合中的第一个子结点的引用
    lastChild 指向子结点结合中的最后一个子结点的引用

    23. 自己练习的一段代码:

    原生的js已经开始支持一些jquery的方法了。

    http://www.cnblogs.com/xiaopen/p/5540884.html

    24.getComputedStyle/currentStyle  http://www.jb51.net/article/78335.htm

     getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式对象([object CSSStyleDeclaration]) 
    currentStyle是IE浏览器的一个属性,返回的是CSS样式对象

    element指JS获取的DOM对象 
    element.style //只能获取内嵌样式 
    element.currentStyle //IE浏览器获取非内嵌样式 
    window.getComputedStyle(element,伪类) //非IE浏览器获取非内嵌样式 
    document.defaultView.getComputedStyle(element,伪类)//非IE浏览器获取非内嵌样式 
    注:Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null),现在可以省略这个参数。

    代码:

    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="Generator" content="EditPlus®">
        <meta name="Author" content="Yvette Lau">
        <meta name="Keywords" content="关键字">
        <meta name="Description" content="描述">
        <title>Document</title>
        <style>
          #test{
            500px;
            height:300px;
            background-color:#CCC;
            float:left;
          }
        </style>
      </head>
      <body>
        <div id = "test"></div>
        <div id = "tag" style = "500px; height:300px;background-color:pink;"></div>
      </body>
    </html>
    

      

    <script type = "text/javascript">
      window.onload = function(){
        var test = document.getElementById("test");
        var tag = document.getElementById("tag");
     
        //CSS样式对象:CSS2Properties{},CSSStyleDeclaration
        console.log(test.style); //火狐返回空对象CSS2Properties{},谷歌返回空对象CSSStyleDeclaration{} 
        console.log(tag.style); //返回CSS2Properties{"500px",height:"300px",background-color:"pink"}
        //element.style获取的是内嵌式的style,如果不是内嵌式,则是一个空对象
     
        console.log(tag.style.backgroundColor);//pink
        console.log(tag.style['background-color']);//pink
        //获取类似background-color,border-radius,padding-left类似样式的两种写法啊
     
        console.log(test.currentStyle) //火狐和谷歌为Undefined,IE返回CSS对象
        console.log(window.getComputedStyle(test,null))//谷歌返回CSSStyleDeclaration{……} ,火狐返回CSS2Properties{……}
        console.log(window.getComputedStyle(test))
        //效果同上,但是在Gecko 2.0 (Firefox 4/Thunderbird 3.3/SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null)
     
        console.log(test.currentStyle.width);//500px(IE)
        console.log(window.getComputedStyle(test).width); //500px;
        console.log(window.getComputedStyle(test)['width']);//500px;
        //document.defaultView.getComputedStyle(element,null)[attr]/window.getComputedStyle(element,null)[attr]   
      }
    </script>
    

      为了简单,我们也可以对获取样式做一个简单的封装。

    function getStyle(element, attr){
          if(element.currentStyle){
            return element.currentStyle[attr];
          }else{
            return window.getComputedStyle(element,null)[attr];
          }
        }
        console.log(getStyle(test,"cssFloat"));//left
        console.log(getStyle(test,"float"));  //left,早前FF和chrome需要使用cssFloat,不过现在已经不必
        console.log(getStyle(test,"stylefloat"));//火狐和谷歌都是undefined
        console.log(getStyle(test,"styleFloat")); //IE9以下必须使用styleFloat,IE9及以上,支持styleFloat和cssFloat
     
        console.log(window.getComputedStyle(test).getPropertyValue("float"))
    

      对应float样式,IE中使用的是styleFloat,而早前的FF和chrome使用的是cssFloat,现在FF和Chrome已经支持float,还有一些其他的属性,不再一一列出,为了不去记忆这些差异点,我们引出两个访问CSS样式对象的方法: 

    getPropertyValue方法和getAttribute方法

    IE9及其它浏览器(getPropertyValue) 
    window.getComputedStyle(element, null).getPropertyValue(“float”); 
    element.currentStyle.getPropertyValue(“float”); 
    getPropertyValue不支持驼峰写法。(兼容IE9及以上,FF,Chrom,Safari,Opera) 
    如:window.getComputedStyle(element,null).getPropertyValue(“background-color”);

    对于IE6~8,需要使用getAttribute方法,用于访问CSS样式对象的属性

    element.currentStyle.getAttribute(“float”);//不再需要写成styleFloat 
    element.currentStyle.getAttribute(“backgroundColor”);//属性名需要写成驼峰写法,否则IE6不支持,如果无视IE6,可以写成”background-color”

    25.事件代理。

    addEventListener这个方法也不能解决未知元素的问题,只能通过在父元素上添加事件,然后通过event.target || event.srcElement;可以获取真正的事件源。

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Document</title>
        <style type="text/css">
        </style>
    </head>
    <body>
        <div id="box">
            <div class="content">hhahha</div>
            <span>这个世界是属于我们的么</span>
        </div>
        <script type="text/javascript">
            window.onload = function(){
                debugger;
                document.querySelector('.content').addEventListener('click',function(){
                    alert("nihao");
                },false);
            }
            var i = 0;
            document.querySelector("#box").onclick = function(event){
                i++;
                //或者事件目标 eventsource这个就是我们的真正产生点击的dom
                var eventsource = event.target || event.srcElement;
                console.log(eventsource);
                //event.target.tagName  这个获取的是标签的名字
                //event.target.innerText 这个获取的是标签的内部
    
                var div = document.createElement("span");
                div.setAttribute('class','content');
                var ss  = document.createTextNode("我们都是好孩子"+i);
                div.appendChild(ss);
                document.querySelector("#box").append(div);
            };
        </script>
    </body>
    </html>
    View Code

     26.js原生获取屏幕的宽度。document.documentElement.clientWidth

  • 相关阅读:
    springboot文件上传: 单个文件上传 和 多个文件上传
    Eclipse:很不错的插件-devStyle,将你的eclipse变成idea风格
    springboot项目搭建:结构和入门程序
    POJ 3169 Layout 差分约束系统
    POJ 3723 Conscription 最小生成树
    POJ 3255 Roadblocks 次短路
    UVA 11367 Full Tank? 最短路
    UVA 10269 Adventure of Super Mario 最短路
    UVA 10603 Fill 最短路
    POJ 2431 Expedition 优先队列
  • 原文地址:https://www.cnblogs.com/coding4/p/5446594.html
Copyright © 2011-2022 走看看