JS-DOM

1.1.什么是DOM 文档对象模型

DOM document object model文档对象模型
DOM规定了一套管理HTML文档的机制,它不是一个对象,主要使用document对象操作文档中的内容,整个文档就是有这些节点构成的树形结构

DOM规定HTML一切内容都称为节点

1)HTML的元素称为元素节点(element node)
2)HTML元素之间的文本称为文本节点(text node)
3)HTML元素的属性称为属性节点(attribute node)
4)HTML文档称为文档节点
5)HTML注释称为注释节点

注意:所有节点都是对象类型,所有节点都包含以下属性:

nodeType:表示节点类型
nodeName:表示节点名称
nodeValue:表示节点值

1.2.节点的三个属性

1.2.1.nodeType:获取节点类型

元素节点返回1
属性节点返回2
文本节点返回3
注释节点返回8
文档节点返回9

1.2.2.nodeName:获取节点名称

元素节点返回元素名称
属性节点返回属性名称
文本节点返回#text
注释节点返回#comment
文档节点返回#document

1.2.3.nodeValue:获取节点值

元素节点返回null
属性节点返回属性值
文本节点返回文本内容
注释节点返回注释内容
文档节点返回null

    <div id="box" title="hello">
        我是一个div节点
    </div><!-- 节点的三个属性-->
<script>
    /*节点的三个属性*/
    //元素节点
    var obj=document.getElementById("box");
    console.log(obj);
    console.log(obj.nodeType);              //1
    console.log(obj.nodeName);              //DIV
    console.log(obj.nodeValue);             //null

    //属性节点
    var attr=obj.getAttributeNode("id");
    console.log(attr);
    console.log(attr.nodeType);              //2
    console.log(attr.nodeName);              //id
    console.log(attr.nodeValue);             //box

    //文本节点
    var txt=obj.firstChild;                 //获取文本节点
    console.log(txt);
    console.log(txt.nodeType);              //3
    console.log(txt.nodeName);              //#text
    console.log(txt.nodeValue);             // <!-- 节点的三个属性-->

    //注释节点
    var com=obj.nextSibling;
    console.log(com);
    console.log(com.nodeType);              //8
    console.log(com.nodeName);              //#comment
    console.log(com.nodeValue);             // 我是一个div节点

    //文档节点
    console.log(document);
    console.log(document.nodeType);              //9
    console.log(document.nodeName);              //#document
    console.log(document.nodeValue);             // null
</script>

1.3 页面元素节点的获取

1.3.1 通过ID获取:document.getElementById(‘idName’)

document.getElementById('idName')
a.获取页面中第一个符合条件的元素
b.区分大小写
c.参数不需要加#
注:加#是css选择器的id选择器,这里是获取id,不是获取选择器,所以不需要加#

1.3.2 通过标签名获取:node.getElementsByTagName(‘tagName’)

node.getElementsByTagName('tagName')
a.返回伪数组类型,可以操作下标,但是数组的方法不能用,
b.不区分大小写

1.3.3.通过name属性获取:document.getElementByName()

a.返回伪数组类型,可以操作下标,但是数组的方法不能用
b.适用于表单元素

1.3.4 通过class属性获取:document.getElementsByClassName()

document.getElementsByClassName('className')
a. 返回伪数组,可以操作下标
b. 有浏览器兼容性,主要ie8以下

1.3.5 通过css选择器获取

document.querySelector('css选择器')
返回符合条件的第一个元素 Id选择器需要加#
document.querySelectorAll('css选择器')
返回符合条件的所有元素,是一个伪数组形式,可以操作下标

1.3.6 getElement和querySelector的区别

getElement:获得的元素是动态的
querySelecto:获得的元素是静态的,所选择出的元素数组不会随着文档的操作而改变

<!--页面元素节点的获取-->
	  <div id="box" title="hello">我是一个div节点</div>
    <div id="box">1</div>
    <div id="box">2</div>
    <p>3</p>
    <p>4</p>
    <input type="checkbox" name="hobby">爬山
    <input type="checkbox" name="hobby">游泳
    <input type="checkbox" name="hobby">唱歌
    <ul>
        <li>我是第1个li</li>
        <li class="sty">我是第2个li</li>
        <li>我是第3个li</li>
        <li class="sty">我是第4个li</li>
        <li>我是第5个li</li>
    </ul>
<script>
    /*页面元素节点的获取*/
    //通过元素id获取
    var id=document.getElementById("box");
    console.log(id);                                //<div id="box" title="hello">

    //通过节点的标签名获取,伪数组,可以用下标来获取页面指定元素节点
    var tag=document.getElementsByTagName("div");
    console.log(tag);                               //获取页面中该标签的所有元素节点
    console.log(tag[0]);                            //<div id="box" title="hello">
    console.log(tag[3]);                            //<div id="boxbox">

    //通过name属性来获取,适用于表单
    var names=document.getElementsByName("hobby");
    console.log(names);                             //伪数组

    //通过class类属性来获取
    var class1=document.getElementsByClassName("sty");
    console.log(class1);                            //伪数组

    //通过类选择器来获取
    var sel1=document.querySelector("div");
    console.log(sel1);                              //<div id="box" title="hello">
    var sel2=document.querySelectorAll("div");
    console.log(sel2);                              //获取页面中该选择器的所有元素节点
</script>

1.4 元素节点中内容的操作

  • innerHTML属性
  1. 能够将标签下面的所有的后代标签和内容一并获取
  2. 能够解析标签
  • innerText属性与textConnect属性类似,用法一致
  1. 只能获取标签下面的文本内容
  2. 不能解析标签
  • value属性:适用于表单
    返回值为字符串类型
<!--元素节点中内容的操作-->
    <div id="box">
        <p>hello</p>
        world
    </div>

    <div id="box2"><p>123</p></div>

    <input type="text" id="user">
    <button>按钮</button>
<script>
//    获取div中的内容
    var div=document.querySelector("div");

    //innerHTML
    var strH=div.innerHTML;
    console.log(strH);               //<p>hello</p>
                                    //world
    //innerText
    var strT=div.innerText;
    console.log(strT);                  //hello
                                        //world
//    设置标签里面的内容
    var div2=document.querySelector("#box2");
    div2.innerHTML="ok";
    div2.innerText="hello";

    div2.innerHTML="<i>ok</i>"
    div2.innerText="<i>ok</i>"

//    value属性
    var btn=document.querySelector("button");
    btn.onclick=function(){
        //获取文本框中的值
        var input=document.querySelector("input");
        console.log(input.value);

        //设置文本框中的值
        input.value="123456";
    }
</script>

1.5 属性节点的获取

  1. 利用元素节点的attributes属性来获取到所有的属性节点,可以使用下标获取某个属性节点
  2. 使用元素节点.getAttributeNode(‘属性名’)方法,获取元素身上的某个属性节点
<!--获取属性节点-->
    <div id="box" title="helloworld"></div>
    
<script>
//    利用元素节点的attributes属性
    var div=document.querySelector("div");
    console.log(div.attributes);                //NamedNodeMap [ id="box", title="helloworld" ]
    console.log(div.attributes[0]);             //id="box"
    
//  元素节点.getAttributeNode('属性名')方法
    console.log(div.getAttributeNode("id"));    //id="box"
</script>

1.6 属性节点值的操作-获取、设置、修改

1. 利用元素节点的方法
a. 获取元素节点某个属性的值,格式:元素节点.getAttribute('属性名称')
b. setAttribute方法设置或修改属性值,格式:元素节点.setAttribute('属性名称', '属性值')
2. 利用属性节点的nodeValue(不常用)
a. 利用属性节点的nodeValue获取属性值
b. 利用属性节点的nodeValue设置或修改属性值
3. 利用点语法(常用):元素节点.属性名称
4. 利用中括号(常用):元素节点['属性名称']
注意:点语法后面不可以加变量,而中括号后面可以加变量
5. 自定义属性的问题
元素节点和属性节点的nodeValue这两种方法可以获得属性节点的值
点语法和中括号这两种方法不能获得属性节点的值

<!--属性值的操作-获取,设置与修改-->
    <div id="box" title="hello" a="100"></div>
<script>
    var div=document.querySelector("div");
//    利用元素节点
    var str=div.getAttribute("id");         //box
    console.log(str);
    div.setAttribute("title","hi");         //<div id="box" title="hi" a="100"></div>

//    利用属性节点的nodeValue
    var attr=div.getAttributeNode("id");            //box
    console.log(attr.nodeValue);
    div.getAttributeNode("id").nodeValue="ok";      //<div id="ok" title="ji" a="100"></div>

//    利用点语法
    console.log(div.id);                        //ok
    div.title="no";                             //<div id="ok" title="no" a="100"></div>

//    利用中括号
    console.log(div["id"]);                     //ok
    div["title"]="yes";                         //<div id="ok" title="yes" a="100"></div>

// 注意:点语法后面不可以加变量,而中括号后面可以加变量
    var str = 'title';
    console.log(div.str);           //undefined
    console.log(div[str]);          //yes          

// 自定义属性的问题
    console.log(div.getAttribute('a'));                 //100
    console.log(div.getAttributeNode('a').nodeValue);   //100
    console.log(div.a);                                 //undefined
    console.log(div['a']);                              //undefined
</script>

6. class属性的操作
a. 如果要使用点语法和中括号的方法操作类,那么不可以直接写class,需要使用className
b. 元素节点和属性节点的nodeValue这两种方法,可以直接写class操作类
7. checked属性和selected属性的操作
使用JavaScript操作表单元素中的checked属性和selected属性,注意:属性值需要设置为true、false
a.true:表示选中
b.false:表示取消选中
即不要用JS写checked="checked"或selected="selected"

//checked属性和selected属性的操作
<input type="checkbox" name="hobby">爬山
<input type="checkbox" name="hobby">游泳
<input type="checkbox" name="hobby">唱歌
<br>
<select name="" id="">
<option value="">100</option>
<option value="">200</option>
<option value="">300</option>
<option value="">400</option>
<option value="">500</option>
</select>
<script>
	var inputs = document.getElementsByName('hobby');
 	inputs[1].checked = true;
	inputs[2].checked = true;
   inputs[2].checked = false;
   var options = document.querySelectorAll('option');
 	 options[2].selected = true;
   options[2].selected = false;
</script>

8. 属性节点的删除与创建
1) removeAttribute方法
a.作用:删除属性节点
b.格式:元素节点.removeAttribute('属性名称');
2) createAttribute方法(不常用)
1.作用:创建属性节点对象,返回值为创建好的属性节点对象
2.格式:document.createAttribute('属性名称');
3.注意:属性节点创建好后,它没有对应属性值,需要调用value属性,为该属性节点添加值,格式:属性节点.value = 值
4.当属性节点对象处理完毕后,可以利用setAttributeNode方法,将这个属性节点添加到HTML元素上,格式:元素节点.setAttributeNode(属性节点对象);

//removeAttribute方法删除属性节点
<div id="box" title="hello"></div>
<script>
    var div = document.getElementById('box');
 	  var res = div.removeAttribute('title');
</script>

//createAttribute方法创建属性节点
    <div id="box"></div>
    <script>
    var div = document.querySelector('#box');    
    // 创建属性节点title
    var res = document.createAttribute('title');
    // 利用value属性为上面的属性节点添加值
    res.value = 'hello';
    // 利用setAttributeNode方法将创建好的属性节点添加到div中
    div.setAttributeNode(res);
</script>

1.7节点关系

页面中的节点不是孤立的,是有关系的,常见的如下
1.childNodes:父元素的所有子节点
2.firstChild:父元素的第一个子节点
3.lastChild;父元素的最后一个子节点
4.parentNode:父节点
5.nextSibling:下一个兄弟节点
6.previousSibling:前一个兄弟节点
注意:换行的文本节点会被包含在内

<!--节点关系-->
    <ul>
        <li>我是第1个li</li>
        <li>我是第2个li</li>
        <li>我是第3个li</li>
        <li>我是第4个li</li>
        <li>我是第5个li</li>
        <li>我是第6个li</li>
        <li>我是第7个li</li>
        <li>我是第8个li</li>
        <li>我是第9个li</li>
        <li>我是第10个li</li>
    </ul>
<script>
    var ul=document.querySelector("ul");
    console.log(ul.childNodes);                 //NodeList(21) [ #text, li, #text, li, #text, li, #text, li, #text, li, … ]
    console.log(ul.firstChild);                 //#text
    console.log(ul.lastChild);                  //#text
    console.log(ul.parentNode);                 //<body>
    console.log(ul.previousSibling);            //#text "
    console.log(ul.nextSibling);                //#text "
    console.log(ul.nextSibling.nextSibling);    //<script>;下一个兄弟节点是空白节点,再下一个节点就是<script>节点
    console.log(ul.previousSibling.previousSibling);    //<!-- 节点关系 -->;上一个节点是空白节点,再上一个节点是注释节点<!-- 节点关系 -->
</script>

1.8 元素节点间的关系:解决换行出现的文本节点的干扰

childNodes----children
firstChild----firstElementChild
lastChild-----lastElementChild
parentNode-----parentElement
nextSibling-----nextElementSibling
previousSibling-----previousElementSiblng

<ul>
        <li>我是第1个li</li>
        <li>我是第2个li</li>
        <li>我是第3个li</li>
        <li>我是第4个li</li>
        <li id="box">我是第5个li</li>
        <li>我是第6个li</li>
        <li>我是第7个li</li>
        <li>我是第8个li</li>
        <li>我是第9个li</li>
        <li>我是第10个li</li>
    </ul>
 
    <script>
        var ul = document.querySelector('ul');

        console.log(ul.childNodes);
        console.log(ul.children);
        console.log('-----------------------');
 
        console.log(ul.firstChild);
        console.log(ul.firstElementChild);
        console.log('-----------------------');
 
        console.log(ul.lastChild);
        console.log(ul.lastElementChild);
        console.log('-----------------------');
 
        console.log(ul.parentNode.parentNode.parentNode);				//#document
        console.log(ul.parentElement.parentElement.parentElement);		//undifinde  获取的是元素节点,而document是文本节点
        console.log('-----------------------');

        var box = document.querySelector('#box');
        console.log(box.previousSibling);
        console.log(box.previousElementSibling);
        console.log('-----------------------');
 
        console.log(box.nextSibling);
        console.log(box.nextElementSibling);
        console.log('-----------------------');

1.9 页面中特殊节点的获取

  1. 获取html节点document.documentElement属性
  2. 获取body节点document.body属性
  3. 获取head节点document.head属性
  4. 获取或设置title节点document.title或document.title = 值;
  5. 文档节点document,也可以使用元素节点的ownerDocument属性获取文档节点(不常用)
// 获取html节点:document.documentElement属性
        console.log(document.documentElement);
// 获取body节点:document.body属性
        console.log(document.body);
// 获取head节点:document.head属性
        console.log(document.head)
// 获取或设置title节点:document.title或document.title = 值;
        console.log(document.title);
        document.title = 'hello';
// 文档节点:document,也可以使用元素节点的ownerDocument属性获取文档节点
     	console.log(document);
       console.log(document.body.ownerDocument);//不常用
  1. document对象的属性如下(了解)
    1) .documentURI:html文档地址
    2) .URL:html文档地址
    3) .domain:返回地址中的域名部分
    4) .lastModified:返回文档上一次修改的时间
    5) .location:返回Location对象,该对象用来操作url地址,包含如下属性和方法
    a. href属性:获取或设置当前地址,能够利用它实现页面跳转
    b. assign方法:设置url地址,格式:document.location.assign('地址');
    注意:
    a. href属性和assign方法在实现页面跳转时都会产生浏览记录
    b. 如果要实现页面跳转,除了用上面的href属性和assign方法,还可以使用window对象的location属性来进行跳转,window.location = '新的地址';
    6) .readyState属性:返回的是页面加载的状态,包含三种状态
    a.loading:表示正在加载html文档,并解析
    b.interactive:表示正在加载外部资源
    c.complete:表示整个文档加载完毕
    如果要看到上面的效果可以
    1.先在NetWork选项卡下面将网速调为slow3G
    2.重新刷新页面
    3.在控制台输入:setInterval(function() {console.log(document.readyState)}, 100),并回车
		console.log(document.documentURI);
        console.log(document.URL);
        console.log(document.domain);
        console.log(document.lastModified);
        console.log(document.location);
        console.log(document.location.href);
        document.location.assign('http://www.baidu.com');
        window.location = 'http://www.baidu.com';
        console.log(document.readyState);
  1. anchors:获取页面中所有的具有name属性的超链接
  2. forms:获取页面中的所有的form节点
  3. images:获取页面中的所有的img节点
  4. links:获取页面中带有href属性的超链接
  5. scripts:获取页面中的所有的script节点
  6. 文档类型声明document.doctype属性
 			 // anchors:获取页面中所有的具有name属性的超链接
        console.log(document.anchors);
        // forms:获取页面中的所有的form节点
        console.log(document.forms);
        // images:获取页面中的所有的img节点
        console.log(document.images)
        // links:获取页面中带有href属性的超链接
        console.log(document.links);
        // scripts:获取页面中的所有的script节点
        console.log(document.scripts);
        // 文档类型声明:document.doctype属性
        console.log(document.doctype);

1.10 DOM操作CSS样式:获取或设置样式

  • 行内样式

如果要使用DOM操作行内样式,可以使用元素节点的style属性来操作

  1. 获取行内样式:
    a. 元素节点.style,返回的是CSS样式声明对象,这个对象中有我们设置的CSS样式
    b. 元素节点.style.CSS属性名称,获取你设置的指定的CSS样式
    c. 元素节点.style.cssText,获取你设置的全部CSS样式
    注意
    如果CSS属性名称由横线连接多个单词,那么需要采用驼峰命名法;
    返回值为由所有行内样式形成的字符串
  2. 设置行内样式:元素节点.style.CSS属性名称 = 值;
    注意:若用元素节点.style.cssText设置行内样式,则原设置的样式清零,更新为当前设置的样式
  3. 行内样式表的对象的方法:操作行内样式的值
    a. 元素节点.style.setProperty(propertyName,value):设置某个CSS属性。
    b. 元素节点.style.getPropertyValue(propertyName):读取某个CSS属性的值。
    c. 元素节点.style.removeProperty(propertyName):删除某个CSS属性。
    注意:如果CSS属性名称由横线连接多个单词,不需要采用驼峰命名法
<div id="box" style="height:200px;width:200px;background:bisque;line-height: 200px;font-size: 50px;">hello</div>
<script>
    var div=document.querySelector("#box");
    //获取
    console.log(div.style);
    console.log(div.style.cssText);
    console.log(div.style.height);
    //设置
    div.style.height="100px";
    div.style.cssText='color:red';
    div.style.cssText="height:200px;width:200px;background:bisque;line-height: 200px;font-size: 50px;color:red;"

    //行内样式表对象的方法,操作样式的值
    //1. 删除
    div.style.removeProperty("color");
    //2. 设置
    div.style.setProperty("color","blue");
    //3. 获取
    var res=div.style.getPropertyValue("color");
    console.log(res);
</script>
  • 内部样式与外部样式:方法一样
  1. getComputedStyle方法
    a. 作用:可以在谷歌浏览器(包含火狐等其它浏览器,但是不包含低版本IE(8以下))获取或者设置外部样式表或内部样式表
    b. 格式:window.getComputedStyle(元素节点, null);
    c. 返回值:返回经过计算的元素身上的所有样式
  2. currentStyle属性
    a. 低版本的IE浏览器下面获取内部或外部样式表
    b. 格式:元素节点.currentStyle
    c. 返回值:返回样式表对象
  3. 获取内部样式或外部样式的兼容写法
    a. 即可以在谷歌浏览器和低版本IE浏览器下获取样式
    b. 方法:创建一个函数
    c. 函数:
    function getStyle(ele, cssName) {
    if (window.getComputedStyle == undefined) {//如果等于undefined,说明是IE
    return ele.currentStyle[cssName]; //注意,此处不可以用点语法,因为点语法不支持变量
    } else {//谷歌浏览器
    return window.getComputedStyle(ele, null)[cssName];
    }
    }
    <style>
        #box{
            width:100px;
            height: 100px;
            line-height: 100px;
            font-size: 30px;
            text-align: center;
            color: #fda;
            background: #aaf;
        }
    </style>
<div id="box">hello</div>
<script>
    //1. 谷歌等浏览器
    var div=document.getElementById("box");
    var obj=window.getComputedStyle(div,null);
    console.log(obj);
    console.log(obj.height);

    //2. 低版本的IE浏览器
    var div=document.getElementById("box");
    var obj=div.currentStyle;
    console.log(obj);
    console.log(obj.height);

    //3. 浏览器的兼容性设置
    function getStyle(ele,cssName){
        if(window.getComputedStyle==undefined){
            //IE浏览器下
            return ele.currentStyle[cssName];       //不能用点语法,因为点语法不适用变量
        }else{
            //谷歌等浏览器下
            return window.getComputedStyle(ele,null)[cssName];
        }
    }
    var div=document.getElementById("box");
    var res=getStyle(div,'height');
    console.log(res);
</script>

1.11 DOM的常用方法

  1. createElement方法
    a. 作用:创建元素节点
    b. 格式:document.createElement('标签名称')
    c. 返回值: 创建好的空白的元素节点
    注意:如果要添加内容可以使用innerHTML属性
  2. appenpChild方法
    a.作用:将某个节点以尾部追加的方式添加到容器中
    b.格式:父节点.appendChild(要被添加的节点);
    c.返回值:被添加的元素节点
    注意:当这个被添加的节点存在时,会被移动到最后
  3. createTextNode方法
    a.作用:创建文本节点
    b.格式:document.createTextNode('文本内容');
    c.返回值:文本节点
<script>
    /*创建元素节点*/
//    创建元素节点
    var div=document.createElement("div");
//    用inner HTML为元素节点添加内容
    div.innerHTML="helloworld";
//    用appenpChild将节点以尾部追加的方式添加到容器中
    var res=document.body.appendChild(div);
    console.log(res);

    /*创建文本节点*/
//    创建文本节点
    var txt=document.createTextNode("ok");
    var res=document.body.appendChild(txt);
    console.log(res);
</script>
  1. cloneNode方法
    a.作用:克隆节点
    b.格式:要被克隆的节点.cloneNode(参数);
    c.参数说明:true(克隆该节点下面的所有的后代节点)、false(默认,只克隆当前节点)
    d.返回值:克隆出来的节点
    注意:如果元素身上有事件,那么事件不会被克隆
//    克隆节点
    var ul=document.querySelector("ul");
    var res1=ul.cloneNode(true);                //<ul>...<ul>
    document.body.appendChild(res1);

    var res2=ul.cloneNode(false);               //<ul><ul>
    document.body.appendChild(res2);
//点击事件
    ul.onclick = function() {
        console.log('helloworld');
    };
    var ul2 = ul.cloneNode(true);
    // 将克隆出来的ul在添加到body中
    document.body.appendChild(ul2);
  1. insertBefore方法
    a.作用:将某个节点插入到目标节点的前面
    b.格式:父节点.insertBefore(要插入的新节点, 目标节点);
<ul>
        <li>我是第1个li</li>
        <li id="box2">我是第2个li</li>
        <li>我是第3个li</li>
        <li>我是第4个li</li>
        <li>我是第5个li</li>
</ul>
<script>
//    insertBefore
    var ul=document.querySelector("ul");    //父节点
    var newli=document.createElement("li"); //新的节点
    newli.innerHTML="我是新的节点";
    var li=document.querySelector("#box2");  //目标节点
    ul.insertBefore(newli,li);
</script>
  1. removeChild方法
    a.作用:删除节点
    b.格式:父节点.removeChild(要被删除的节点);
    c.返回值:被删除的元素
    注意:被删除的元素被保存在内存中,可以重新调用
  2. replaceChild方法
    a.作用:替换某个节点
    b.格式:父节点.replaceChild(新的节点,旧的节点);
    c.返回值:被替换掉的节点
//    removeChild
    var ul=document.querySelector("ul");    //父节点
    var li=document.querySelector("#box2"); //要被删除的节点
    var res=ul.removeChild(li);
    console.log(res);                       //<li id="box2">
    ul.appendChild(li);                     //重新添加回去
  1. isEqualNode()方法
    a.作用:判断两个节点是否相等
    b.格式:节点1.isEqualNode(节点2);
    c.返回值:true、false
  2. contains方法
    a.作用:判断某个节点是否包含另外的某个指定的节点
    b.格式:节点1.contains(可能包含的节点);
    c.返回值:true(包含)、false(不包含)
  3. hasChildNodes()方法
    a.作用:判断是否有子节点(true,false)
    b.格式:节点.hasChildNodes();
    c.true(表示该元素不是一个空元素)、false(表示该元素是一个空元素)
//      两个节点是否相等
    var eq=ul.isEqualNode(li);
    console.log(eq);                           //false
//    是否包含另一个节点
    var contains=ul.contains(li);
    console.log(contains);                      //true
//    是否含有子节点
    var has=ul.hasChildNodes();
    console.log(has);                           //true

1.12 DOM的常用属性

  1. offsetParent属性:返回的是样式偏移时的参照物
    a.如果元素没有祖先元素,那么返回的是body
    b.如果元素有祖先元素,但是祖先元素没有定位,那么返回的是body
    c.如果元素有祖先元素,且祖先元素有定位,那么返回的是具有定位的且离该元素最近的祖先元素
  2. offsetTop:距离偏移对象顶部的距离
    offsetLeft:距离偏移对象左侧的距离
    格式:元素节点.offsetTop或元素节点.offsetLeft
<style>
        #box {
            width: 200px;
            height: 200px;
            background-color: #f00;
        }
        #boxbox {
            width: 300px;
            height: 300px;
            background-color: blue;
            position: relative;
        }
</style>
<div id="boxbox">
        <div id="box"></div>
</div>
<script>
 var box = document.getElementById('box');
 console.log(box.offsetParent);
 var box = document.querySelector('#box');
console.log(box.offsetParent);
console.log(box.offsetTop);
console.log(box.offsetLeft);
</script>
  1. offsetWidth //返回元素的宽度(包括元素宽度、内边距和边框,不包括外边距,不受滚动条影响)
  2. offsetHeight //返回元素的高度(包括元素高度、内边距和边框,不包括外边距,不受滚动条影响)
  3. clientHeight //返回元素的高度(包括元素高度、内边距,不包括边框和外边距,受滚动条影响)
  4. clientWidth //返回元素的宽度(包括元素宽度、内边距,不包括边框和外边距,受滚动条影响)
    注意
    1.如果要获取页面视口的宽度和高度,那么推荐用clientWidth与clientHeight,如果要获取元素的宽度和高度推荐用offsetWidth和offsetHeight
    2.如果要获取视口的宽度和高度,需要采用如下方式
    视口宽度:var 变量名称 = document.documentElement.clientWidth || document.body.clientWidth;
    视口高度:var 变量名称 = document.documentElement.clientHeight || document.body.clientHeight;
    <style>
        #box {
            width: 200px;
            height: 300px;
            background-color: #f00;
            padding: 50px;
            border: 5px solid;
            margin: 20px; 
            overflow: scroll;
        }
    </style>
<body>
    <div id="box">测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本</div>
<script>
	var div = document.querySelector('#box');
	console.log('offsetWidth = ' + div.offsetWidth);
	console.log('offsetHeight = ' + div.offsetHeight);
	console.log('clientWidth = ' + div.clientWidth);
	console.log('clientHeight = ' + div.clientHeight);
	var viewWidth = document.documentElement.clientWidth || document.body.clientWidth;
	var viewHeight = document.documentElement.clientHeight || document.body.clientHeight;
	console.log(viewWidth, viewHeight);
</script>
</body>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值