JavaScrip之BOM、DOM

BOM

浏览器对象模型(BrowserObjectModel),可以对浏览器窗口进行访问和操作。使用 BOM,开发者可以移动窗口、改变状态栏中的文本以及执行其他与页面内容不直接相关的动作。

使 JavaScript 有能力与浏览器“对话”。 从而提供与浏览器交互的方法和接口。

window对象

所有浏览器都支持 window 对象。它表示浏览器窗口。
所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。
全局变量是 window 对象的属性。
全局函数是 window 对象的方法。
甚至 HTML DOM 的 document 也是 window 对象的属性之一。
概念上讲.一个html文档对应一个window对象。
功能上讲: 控制浏览器窗口的。
使用上讲: window对象不需要创建对象,直接使用即可。

window对象方法:

alert()            显示带有一段消息和一个确认按钮的警告框。
confirm()          显示带有一段消息以及确认按钮和取消按钮的对话框。其方法有返回值,布尔值(确定true取消false)
prompt()           显示可提示用户输入的对话框其方法有返回值,输入有内容,即返回内容;点取消则返回null
open()             打开一个新的浏览器窗口或查找一个已命名的窗口。
close()            关闭浏览器窗口。
setInterval()      按照指定的周期(以毫秒计)来调用函数或计算表达式。
clearInterval()    取消由 setInterval() 设置的 timeout。
setTimeout()       在指定的毫秒数后调用函数或计算表达式。
clearTimeout()     取消由 setTimeout() 方法设置的 timeout。
scrollTo()         把内容滚动到指定的坐标。

示例:

// 在输入框,实现点击显示当前时间,并有stop按钮

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #show{
            width: 200px;
            height: 50px;
        }
    </style>
</head>
<body>
    <input type="text" id="show" onclick="begin()">  <!--绑定点击事件并触发begin函数-->
    <button onclick="end()">Stop</button>            <!--绑定点击事件并触发end函数-->

    <script>
        function showtime() {
            var date_time = new Date().toLocaleString();    // 获取当前事件
            var content = document.getElementById("show");  // 找到id为。。的标签
            content.value = date_time;                      // 对标签的value进行赋值
        }

        var clock;   // 声明变量
        function begin() {
            // 变量未被定义则为undefined
            if (clock==undefined){
                showtime();  // 执行函数
                clock = setInterval(showtime,1000);  // 多次计时 单位毫秒
            }
        }

        function end() {
            clearInterval(clock);  // 清空多次定时器
            clock=undefined;       // 重新赋值
            }
    </script>
</body>
</html>
setInterval clearInterval之多次定时器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button onclick="f1()">点我</button>
    <button onclick="f2()">停止</button>


    <script>
        var my_var;
        function f1() {
            my_var = setTimeout(function () {alert("Hello World")},3000);
            // 等待三秒  弹出框Hello World
        }

        function f2() {
            clearTimeout(my_var);
            // 清除单次计时器
            // 且必须在3000毫秒之前点击 否则无效
        }

    </script>
</body>
</html>
setTimeout clearTimeout之单次定时器

history

History 对象包含用户(在浏览器窗口中)访问过的 URL。

History 对象是 window 对象的一部分,可通过 window.history 属性对其进行访问。

length  返回浏览器历史列表中的 URL 数量。

history方法:

back()          加载 history 列表中的前一个 URL。
forward()       加载 history 列表中的下一个 URL。
go()            加载 history 列表中的某个具体页面。 
<a href="rrr.html">click</a>
<button onclick=" history.forward()">>>></button>
<button onclick="history.back()">back</button>
<button onclick="history.go()">back</button>

// go里面的参数 1 和 -1 对应    
示例

location

Location 对象包含有关当前 URL 的信息。

Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问。编写时可不使用 window 这个前缀。

Location提供的方法

  • location.hostname 返回 web 主机的域名
  • location.pathname 返回当前页面的路径和文件名
  • location.port 返回 web 主机的端口 (80 或 443)
  • location.protocol 返回所使用的 web 协议(http:// 或 https://)
  • location.assign(URL) 加载新文档
  • location.replace(newurl) 加载新文档
  • location.reload() 重新加载 类似于浏览器刷新的快捷键F5
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <button onclick="newurl()">加载assign文档</button>
    <button onclick="myurl()">加载replace文档</button>
    <button onclick="flush()">刷新文档</button>
    <script>
        console.log(location.hostname);
        console.log(location.pathname);
        console.log(location.port);
        console.log(location.protocol);
        console.log(location.href);
        // assign
        function newurl() {
            location.assign("http://www.xiaohuar.com/")
        }

        // replace
        function myurl() {
            location.replace("http://www.xiaohuar.com/")
        }
        // assign与replace的区别  assign可返回 replace不可返回上个url

        // reload
        function flush() {
            location.reload()
        }

    </script>
</body>
</html>
示例

DOM

HTML DOM(文档对象模型)

当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。

HTML DOM 模型被构造为对象的树。

查找页面内元素的时候,把<script>......</script>放在被查找的标签后面。

DOM树

DOM节点

根据W3C和HTML DOM标准,HTML文档中的所有内容都是节点(NODE)

  1. - 整个HTML文档是一个文档节点(document对象)
  2. - 每个 HTML 元素是元素节点(element 对象)
  3. - HTML 元素内的文本是文本节点(text对象)
  4. - 每个 HTML 属性是属性节点(attribute对象)
  5. - 注释是注释节点(comment对象)

本文主要学习前两个,我们可以通过"对象.属性"的方式来找对应的文本对象和属性对象。

节点关系

节点树中的节点彼此拥有层级关系。
父(parent),子(child)和同胞(sibling)等术语用于描述这些关系。父节点拥有子节点。同级的子节点被称为同胞(兄弟或姐妹)。

  •     在节点树中,顶端节点被称为根(root)
  •     每个节点都有父节点、除了根(它没有父节点)
  •     一个节点可拥有任意数量的子
  •     同胞是拥有相同父节点的节点

下面的图片展示了节点树的一部分,以及节点之间的关系:

查找HTML元素

通常,通过 JavaScript,您需要操作 HTML 元素。
为了做到这件事情,您必须首先找到该元素。常用有三种方法来做这件事:

 直接查找

document.getElementById             根据ID获取一个标签
document.getElementsByName          根据name属性获取标签集合
document.getElementsByClassName     根据class属性获取标签集合
document.getElementsByTagName       根据标签名获取标签集合
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="c1">
    <h1 id="d1">HHHH</h1>
    <a href="" class="c2">AAAA</a>
    <p>PPPP</p>
</div>
</body>
</html>
示例代码

间接查找

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

:如果未找到则是返回的null值

标签操作

 内容操作:

innerText  文本内容
 
innerHTML   HTML内容
    ele_h1=document.getElementById('d1');
    ele_div1=document.getElementsByClassName('c1');
    console.log(ele_h1.innerText);   
    // HHHH
    console.log(ele_h1.innerHTML);   
    // HHHH
    console.log(ele_div1[0].innerText);  
    // HHHH AAAA PPPP
    console.log(ele_div1[0].innerHTML); 
    //<h1 id="d1">HHHH</h1><a href="" class="c2">AAAA</a><p>PPPP</p>
示例
    ele_h1=document.getElementById('d1');
    ele_h1.innerText='hhhh'
    ele_h1.innerHTML='hh<br>hh'
示例

属性操作:

原生JS方式:
element.setAttribute(name,value)    
element.getAttribute(属性名) 					
				       
DHTML的简化方式:
element.属性名
element.属性名="值"

 简化方式有很多不支持的属性操作,比如class属性等。我们可以使用classList.add() 和classList.remove()来操作class属性。

ele_h1=document.getElementById('d1');
console.log(ele_h1.getAttribute('id'));     // d1
ele_h1.setAttribute('very','good');         // 添加very属性 值为good
console.log(ele_h1.getAttribute('very'));   // good
ele_h1.classList.add('cc');                 // 添加class属性 值为cc
console.log(ele_h1.className);              // cc
console.log(ele_h1.class);                  // undefined
console.log(ele_h1.id);                     // d1          
示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
          .left{
              width: 20%;
              height: 500px;
              float: left;
              background-color: wheat;
          }

          .right{
              float: left;
              width: 80%;
              height: 500px;
              background-color: lightgray;
          }

           .title{
               text-align: center;
               line-height: 40px;
               background-color: #0e90d2;
               color: white;
           }
        .item{
            padding: 10px;
        }
    <!--隐藏-->
        .hide{
            display: none; 
        }
    </style>
</head>
<body>
<div class="outer">
      <div class="left">
           <div class="item">
               <div class="title">菜单一</div>
               <ul class="con">
                   <li>111</li>
                   <li>111</li>
                   <li>111</li>
               </ul>
           </div>
          <div class="item">
               <div class="title">菜单二</div>
               <ul class="con hide">
                   <li>222</li>
                   <li>222</li>
                   <li>222</li>
               </ul>
           </div>
          <div class="item">
               <div class="title">菜单三</div>
               <ul class="con hide">
                   <li>333</li>
                   <li>333</li>
                   <li>333</li>
               </ul>
           </div>
      </div>
      <div class="right"></div>
</div>
<script>
// 先找到菜单对象,将下面的内容全部展开,筛选出没有被点击的通过classList.add添加隐藏属性 'hide'
    var eles_title=document.getElementsByClassName("title");
    
    for (var i=0;i<eles_title.length;i++){
        
         eles_title[i].onclick=function(){
             
             this.nextElementSibling.classList.remove("hide");
             
             for(var j=0;j<eles_title.length;j++){
                 
                 if (eles_title[j]!=this){
                     
                     eles_title[j].nextElementSibling.classList.add("hide")
                 }
             }
         }
    }
    
</script>
</body>
</html>
左侧菜单示例

style操作,改变HTML的CSS样式:

document.getElementById(id).style.css属性='样式值'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>改变HTML的CSS样式:</title>
</head>
<body>
<p id="p1">hello</p>
<button>变绿</button>
<script>
    var eles_button=document.getElementsByTagName('button')[0];
    var ele_p=document.getElementById('p1');
    eles_button.onclick=function(){
        ele_p.style.color='green'
    }
</script>
</body>
</html>
给你添点绿

value操作:

        1.input   
        2.select 
        3.textarea 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" value="hello" id="hi">
<script>
    ele_hi=document.getElementById('hi');
    console.log(ele_hi.value);  // hello
    ele_hi.value='bye';  //input框内将显示bye
</script>
</body>
</html>
input 的value
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select name="" id="s1" >
    <option value="hi">你好</option>
    <option value="bye">再见</option>
</select>
<script>
    // 注意 select 标签也可以.value
    // 默认选中是'你好',所有打印'hi'
    ele_s=document.getElementById('s1');
    console.log(ele_s.value); // hi
</script>
</body>
</html>
select的value
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模拟对话框</title>
    <style>
        .back{
            background-color: white;
            height: 2000px;
        }

        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left:0;
            right: 0;
            background-color: grey;
            opacity: 0.4;   /* 透明度 */
        }

        .hide{
            display: none;
        }

        .models{
            position: fixed;
            top: 50%;
            left: 50%;   /* 盒子左上角居中 */
            margin-left: -100px;
            margin-top: -100px;  /* 调整布局使盒子居中 */
            height: 200px;
            width: 200px;
            background-color: wheat;
        }
    </style>
</head>
<body>
<div class="back">
    <input class="c" type="button" value="click">
</div>

<div class="shade hide handles"></div>

<div class="models hide handles">
    <input class="c" type="button" value="cancel">
</div>
<script>
// 思路:总共三部分,遮罩层与取消是默认隐藏的,通过input的value值判断
// 将哪个标签隐藏, 掌握 classList.remov()与classList.add()。

    var eles=document.getElementsByClassName("c");
    var handles=document.getElementsByClassName("handles");
    for(var i=0;i<eles.length;i++){
        eles[i].onclick=function(){

            if(this.value=="click"){

                for(var j=0;j<handles.length;j++){
                    handles[j].classList.remove("hide");

                 }
            }
            else {
                for(var j=0;j<handles.length;j++){

                    handles[j].classList.add("hide");
                }

            }
        }
    }
</script>
</body>
</html>
运用.classList()与value实现模拟对话框

节点的增与删

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>

<script>
// 创建节点(标签)
var new_p=document.createElement("p");

// 新建内容
var new_content=document.createTextNode("这是一个新段落。");

// 新内容添加到刚刚创建的节点
new_p.appendChild(new_content);
//new_p.style.color='red' 
//new_p.setAttribute('style','color:red')

// 最后将创建的节点作为子节点追加到HTML的一个节点。
var ele_div=document.getElementById("div1");
ele_div.appendChild(new_p);
    
</script>
</body>
</html>
div下追加一个段落
var ele_p2=document.getElementById('p2');
ele_div.insertBefore(new_p,ele_p2)
上面示例,需求改为指定位置增加节点
<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>

<script>
    ele_div1=document.getElementById('div1');
    ele_p1=document.getElementById('p1');
    ele_div1.removeChild(ele_p1);
</script>
删除第一个段落

DOM Event

Event 对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。

事件绑定的两种方式:

方式1(推荐):

<body>
<p id="p1">hello</p>
<script>
    var ele_p=document.getElementById('p1');
    ele_p.onclick=function(){
        console.log(this)   // <p id="p1">hello</p>
    };
</script>
</body>

方式2:

<body>
<p id="p1" onclick="foo(this)">hello</p>
<script>
    function foo(self){     // self是形参 可以是任意变量名,但不可以this。
        console.log(self)  // <p id="p1" onclick="foo(this)">hello</p>
    };
</script>
属性此事件发生在何时...
onabort 图像的加载被中断。
onblur 元素失去焦点。
onchange 域的内容被改变。
onclick 当用户点击某个对象时调用的事件句柄。
ondblclick 当用户双击某个对象时调用的事件句柄。
onerror 在加载文档或图像时发生错误。
onfocus 元素获得焦点。
onkeydown 某个键盘按键被按下。
onkeypress 某个键盘按键被按下并松开。
onkeyup 某个键盘按键被松开。
onload 一张页面或一幅图像完成加载。
onmousedown 鼠标按钮被按下。
onmousemove 鼠标被移动。
onmouseout 鼠标从某元素移开。
onmouseover 鼠标移到某元素之上。
onmouseup 鼠标按键被松开。
onreset 重置按钮被点击。
onresize 窗口或框架被重新调整大小。
onselect 文本被选中。
onsubmit 确认按钮被点击。
onunload 用户退出页面。

onsubmit、onfocus、onblur

当表单在提交时触发. onsubmit也只能给form元素使用.应用场景: 在表单提交前验证用户输入是否正确.如果验证失败.在该方法中我们应该阻止表单的提交.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>

<form action="" id="form">
    <p><input type="text" id="inptext"><span class="error"></span></p>

    <input type="submit">
</form>


<script>
    //onsubmint是由点击<input type="submit">按钮触发的
    function foo() {
        ele_error.innerText = "";
    }
    var ele_form = document.getElementById("form");
    var ele_inptext = document.getElementById("inptext");
    var ele_error = document.getElementsByClassName("error")[0];
    ele_form.onsubmit = function () {
        var inp_value = ele_inptext.value;
        if (inp_value.length > 5 && inp_value.length < 12) {
        }
        else {

            ele_error.innerText = "用户名的长度有问题";
            setTimeout(foo, 3000);
            return false; // 阻止默认事件
        }
    }
</script>
</body>
</html>
input标签设置格式检测(onsubmit)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>

        window.onload=function(){
            //阻止表单提交方式1().
            //onsubmit 命名的事件函数,可以接受返回值. 其中返回false表示拦截表单提交.其他为放行.

             var ele=document.getElementById("form");
             ele.onsubmit=function(event) {
            //    alert("验证失败 表单不会提交!");
            //    return false;

            // 阻止表单提交方式2 event.preventDefault(); ==>通知浏览器不要执行与事件关联的默认动作。
             alert("验证失败 表单不会提交!");
             event.preventDefault();

    }

        };

    </script>
</head>
<body>

<form id="form">
            <input type="text"/>
            <input type="submit" value="点我!" />
</form>

</body>
</html>
阻止表单提交的阿示例2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="text" id="inp1" value="请输入用户名">
<script>

     var ele_inp=document.getElementById("inp1");
// 鼠标获取焦点时,清空提示语
     ele_inp.onfocus=function () {
              this.value="";
     };
// 鼠标失去焦点时,如果没输入用户名或为空格,提示输入用户名
     ele_inp.onblur=function () {
// trim()去空格
         if(!this.value.trim()){
              this.value="请输入用户名"
         }
     }
</script>
</body>
</html>
onfocus、onblur实现输入框输入提示

onchange

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<select name="pro" id="s1">
    <option value="">请选择省份</option>
    <option value="1">河南省</option>
    <option value="2">湖南省</option>
    <option value="3">海南省</option>
</select>

<select name="city" id="s2">
    <option value="">请选择城市</option>


</select>


<script>
    var data = {"1": ["洛阳", "信阳", "开封"], "2": ["长沙", "张家界"], "3": ["三亚", "海口"]};

    var ele_s1 = document.getElementById("s1");
    var ele_s2 = document.getElementById("s2");
    ele_s1.onchange = function () {
        //console.log(this.value);
        var citys = data[this.value];
        //console.log(citys);

//        console.log(ele_s2.children.length);
//        console.log(ele_s2.options.length);

        ele_s2.options.length = 1;
        // ele_s2.children.length=1;
        for (var i = 0; i < citys.length; i++) {
            var city_val = citys[i];
            var ele_option = document.createElement("option");  // <option></option>
            ele_option.innerHTML = city_val;
            //console.log(ele_option);
            ele_s2.appendChild(ele_option)
        }

    }
</script>

</body>
</html>
省市二级联动
原文地址:https://www.cnblogs.com/0bug/p/7821966.html