zoukankan      html  css  js  c++  java
  • JS DOM属性,包括固有属性和自定义属性,以及属性获取、移除和设置

    属性分为固有属性property和自定义属性attribute

    固有属性查看

     固有属性可以通过ele.property 来获取,自定义属性不行

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var input=document.querySelector("input");
                console.log(input.type);//text
                console.log(input.value);//txt
                console.log(input.a);//undefined
                console.log(input.title);//""
    
            });
    
        </script>
    </head>
    <body>
        <input type="text" value="txt" a="b">
    </body>
    </html>

    .attributes 返回类数组,获取所有属性,包括自定义属性和固有属性

    如果定义了同名属性,后面的属性会被忽略

    如果自定义属性时出现了大写,会统一转为小写

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.querySelector("#div");
                console.log(div.attributes);//
    
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html" aa="xx" Bb="yy" aa="zz">这是div</div>
    </body>
    </html>

     获取指定的自定义属性的属性值

    ele.attributes.getNamedItem(属性名).nodeValue

    ele.attributes[属性名].nodeValue

    注意,如果某个固有属性没有在元素中被人为定义,则不可获取

    如果是人为定义的固有属性,或者自定义属性,则可以用该方法获取

    .nodeName 获取元素的节点名

    ele.attributes.removeNamedItem(属性名)   移除属性

    创建属性:

    1、.createAttribute(属性名)  创建属性

    2、attr.value=属性值   给创建的属性设置属性值

    3、.attributes.setNamedItem(属性名,属性值)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.querySelector("#div");
                //获取自定义属性方法一
                console.log(div.attributes.getNamedItem("aa").nodeValue);//xx
                //获取自定义属性方法二
                console.log(div.attributes["aa"].nodeValue);//xx
                //获取未人为定义的固有属性
                console.log(div.attributes.getNamedItem("nodeName"));//null
                //获取固有属性的正确打开方式
                console.log(div.nodeName);//DIV
                //获取人为定义的固有属性
                console.log(div.attributes.getNamedItem("id").nodeValue);//div
    
                // 移除属性
                div.attributes.removeNamedItem("bb");
                console.log(div.attributes);
    
                //创建属性
                var attr=document.createAttribute("data-my");
                attr.value="myattr";
                div.attributes.setNamedItem(attr);
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html" aa="xx" Bb="yy" aa="zz">这是div</div>
    </body>
    </html>

    获取未人为定义的固有属性,返回null

    获取未人为定义的固有属性的nodeValue,会报错

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.querySelector("#div");
    
                //获取未人为定义的固有属性
                console.log(div.attributes.getNamedItem("title"));//null
                console.log(div.attributes.getNamedItem("title").nodeValue);//报错
    
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html" aa="xx" Bb="yy" aa="zz">这是div</div>
    </body>
    </html>

     用.innerHTML来操作固有属性

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.querySelector("#div");
                div.innerHTML="这是innerHTML设置的文本哈";
                console.log(div.innerHTML);//这是innerHTML设置的文本哈
    
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html" aa="xx" Bb="yy" aa="zz">这是div</div>
    </body>
    </html>

    通用方法操作固有属性和自定义属性

    getAttribute()

    setAttribute()

    removeAttribute()

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.querySelector("#div");
                console.log(div.getAttribute("aa"));//xx
    
                console.log(div.getAttribute("style"));//color:orange
                console.log(div.style);//CSSStyleDeclaration {0: "color", alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}
    
                console.log(div.getAttribute("onclick"));//alert('hello~')
                console.log(div.onclick);//onclick(event) {alert('hello~')}
    
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html" aa="xx" Bb="yy" aa="zz" style="color:orange" onclick="alert('hello~')">这是div</div>
    </body>
    </html>

    以上代码表明,使用getAttribute() 和 .属性名  来获取属性值,在某些情况下结果是不同的,比如style和Onclick

    通常,获取固有属性使用 .属性名,获取自定义属性使用getAttribute()

    setAttribute() 设置自定义属性时,不存在兼容性问题

    但是设置部分固有属性,比如onclick和style时,在IE7及以下版本存在兼容性问题

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.querySelector("#div");
                // 设置自定义属性
                div.setAttribute("data-a","a");
                div.setAttribute("style","color:purple");
                div.setAttribute("onclick","alert(0)");
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html">这是div</div>
    </body>
    </html>

    正常浏览器效果

     IE7及以下效果

     由于不支持querySelector方法,先改成document.getElementById()

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.getElementById("div");
                // 设置自定义属性
                div.setAttribute("data-a","a");
                div.setAttribute("style","color:purple");
                div.setAttribute("onclick","alert(0)");
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html">这是div</div>
    </body>
    </html>

    不再报错,但设置的style属性和onclick方法都没有生效

    removeAttribute() 删除属性,不存在兼容性问题

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var div=document.getElementById("div");
                // 设置自定义属性
                div.removeAttribute("style");
            });
    
        </script>
    </head>
    <body>
        <div id="div" url="index.html" style="color:orange">这是div</div>
    </body>
    </html>

     布尔属性

    通过布尔属性操作DOM

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var inputs=document.querySelectorAll("input");
                inputs[0].checked=true;
            });
    
        </script>
    </head>
    <body>
        <input type="checkbox" name="city">杭州
        <input type="checkbox" name="city" checked="checked">宁波
        <input type="checkbox" name="city" checked>温州
    </body>
    </html>

     input.checked 设置成任何非空字符串,都换转为布尔值true,都可以选中

    但这种自动转换在IE7以下会失败

    另外固有属性不能通过removeAttribute() 来移除

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var inputs=document.querySelectorAll("input");
                inputs[0].checked=true;
                inputs[0].checked="checked";
                inputs[0].checked=1;
    
                inputs[1].checked=0;
                inputs[1].checked="";
    
                inputs[1].removeAttribute("checked");
            });
    
        </script>
    </head>
    <body>
        <input type="checkbox" name="city">杭州
        <input type="checkbox" name="city" checked="checked">宁波
        <input type="checkbox" name="city" checked>温州
    </body>
    </html>

    .options 可以获取select下的所有option选项

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var select=document.getElementById("select");
                var options=select.options;
                options[1].selected=true;
            });
    
        </script>
    </head>
    <body>
        <select name="select" id="select">
            <option value="">请选择</option>
            <option value="1">杭州</option>
            <option value="2">宁波</option>
            <option value="3">温州</option>
        </select>
    </body>
    </html>

     .readOnly 只读属性 (注意O必须大写)

    .disabled 禁用属性

    区别:readOnly数据可以提交到服务器,disabled数据不会提交到服务器

    select的multiple属性  设置多选,下拉框变列表框

    HTML5新增属性hidden  使元素不再显示(低版本IE无法兼容)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
            input{
                display: block;
                margin-bottom:10px;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var input=document.getElementById("input");
                input.readOnly=false;
    
                var input2=document.getElementById("input2");
                input2.disabled=true;
    
                var select=document.getElementById("select");
                select.multiple=true;
    
                var div=document.getElementById("div");
                div.hidden=false;
            });
    
        </script>
    </head>
    <body>
        <input type="text" value="中国" readonly id="input">
        <input type="text" value="中国" id="input2">
        <select name="select" id="select">
            <option>杭州</option>
            <option>宁波</option>
            <option>温州</option>
        </select>
        <div id="div" hidden="hidden">这是div</div>
    </body>
    </html>

     常见的字符串属性(大部分都是字符串属性)

    id  唯一标识

    class  类

    href  多用于a链接和link

    src  多用于img和script和video等等

    lang  辅助搜索引擎等的语言识别  <html land="zh">

    zh 中文  zh-cn 中文简体  zh-sg  新加坡  zh-hk  香港

    accesskey  组合键,快捷键

    在谷歌浏览器中使用alt+设置的快捷键字母来激活

    name  多用于表单元素的控件名称

    value  表单元素的值

    title 元素不可见时的提示信息


    W3C全局属性

    accesskey   class  dir  id  lang  title

    contenteditable  元素内容是否可编辑

    hidden  元素是否隐藏

    spellcheck 元素内容编辑时的语法检查

    style  样式

    tabindex  使用tab键导航时的切换顺序


    当一个页面中有多个元素使用相同的id时,使用document.getElementById()能够取得元素,但是只会取得第一个

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
            input{
                display: block;
                margin-bottom:10px;
            }
            .active{
                color:orange;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
                var p=document.getElementById("p");
                console.log(p);//<p id="p">这是一段文字1</p>
    
                var p=document.getElementById("p");
                p.className="active";
            });
    
        </script>
    </head>
    <body>
        <p id="p">这是一段文字1</p>
        <p id="p">这是一段文字2</p>
        
        <input type="text" accesskey="n" value="n"><!-- alt+n -->
        <input type="text" accesskey="m" value="m"><!-- alt+m -->
    </body>
    </html>

     data属性  以data-开头

    设置时多单词以连字符分开,如data-aa-bb

    JS获取时使用dataset.属性名  后面需要转换成小驼峰形式

    但是IE浏览器兼容性不是很好

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
            input{
                display: block;
                margin-bottom:10px;
            }
            .active{
                color:orange;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
    
                var div=document.getElementById("div");
                console.log(div.dataset.toggle);//modal
                console.log(div.dataset.xxxYyy);//aa
            });
    
        </script>
    </head>
    <body>
    
        <div id="div" data-toggle="modal" data-xxx-yyy="aa">这是验证data属性的div</div>
    </body>
    </html>

    class属性

    自定义class相关的操作方法

    this指向当前对象

    gi表示全局匹配且不区分大小写

    str.replace(exp,str2)  将str字符串中,满足exp正则匹配的部分,用str2替换

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
            input{
                display: block;
                margin-bottom:10px;
            }
            .active{
                color:orange;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
    
                var classMethod={
                    //获取class
                    getClass:function(ele){
                        // 将多个空格统一转换为一个空格,并根据空格来将字符串转为数组
                        return ele.className.replace(/s+/," ").split(" ");
                    },
                    //判断是否存在某个class
                    hasClass:function(ele,cls){
                        // 给获取的class字符串前后加上空格,再给要查找的类名前后也加上空格
                        // -1表示不存在,否则为存在
                        return -1< (" "+ele.className+" ").indexOf(" "+cls+" ");
                    },
                    //添加class
                    addClass:function(ele,cls){
                        //this指向classMethod这个对象
                        if(!this.hasClass(ele,cls)){
                            ele.className+=" "+cls;
                        }
                    },
                    //删除class
                    removeClass:function(ele,cls){
                        if(this.hasClass(ele,cls)){
                            //gi表示全局匹配,且不区分大小写
                            var exp=new RegExp("(^|\s)"+cls+"($|\s)","gi");
                            ele.className=ele.className.replace(exp," ");
                        }
                    },
                    //切换class
                    toggleClass(ele,cls){
                        if(this.hasClass(ele,cls)){
                            this.removeClass(ele.cls);
                        }else{
                            this.addClass(ele,cls);
                        }
                    }
                }
    
                var div=document.querySelector("div");
                console.log(classMethod.getClass(div));//(3) ["a", "b", "c"]
    
                console.log(classMethod.hasClass(div,"a"));//true
                console.log(classMethod.hasClass(div,"z"));//false
    
                classMethod.addClass(div,"z");
    
                classMethod.removeClass(div,"z");
    
                classMethod.toggleClass(div,"z");
            });
    
        </script>
    </head>
    <body>
    
        <div class="a b c">这是测试class相关的div</div>
    </body>
    </html>

    js自带的classList对于class的操作

    ele.classList.add(cls)

    ele.classList.remove(cls)

    ele.classList.toggle(cls)

    ele.classList.contains(cls)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            body{
                width:100%;
                height:100%;
            }
            input{
                display: block;
                margin-bottom:10px;
            }
            .active{
                color:orange;
            }
        </style>
        <script src="DomReady.js"></script>
        <script>
            myReady(function(){
    
                var div=document.querySelector("div");
                console.log(div.classList.add("z"));
                console.log(div.classList.toString());//a b c z
    
                console.log(div.classList.remove("a"));
                console.log(div.classList.toString());//b c z
    
                console.log(div.classList.contains("b"));//true
                console.log(div.classList.toString());//b c z
    
                console.log(div.classList.toggle("c"));//false
                console.log(div.classList.toString());//b z
            });
    
        </script>
    </head>
    <body>
    
        <div class="a b c">这是测试class相关的div</div>
    </body>
    </html>

     可惜兼容性是:IE11+

  • 相关阅读:
    beta分布
    python中os.walk浏览目录和文件
    (zz)Linux下Gcc生成和使用静态库和动态库详解
    GNU scientific library
    python 字典有序无序及查找效率,hash表
    Python代码分析工具之dis模块
    python里的坑。http://www.pythoner.com/356.html
    python实现单向链表
    Python 执行字符串表达式函数(eval exec execfile)
    版本管理神器git上手
  • 原文地址:https://www.cnblogs.com/chenyingying0/p/12274488.html
Copyright © 2011-2022 走看看