Web08--JavaScript高级

1、BOM对象

BOM:browser object model   浏览器对象模型

BOM对象包括window对象、screen对象、history对象、location对象、navigator对象。

1.1 window对象

所有的浏览器都支持window对象。它表示的浏览器窗口

window对象是js中的顶层对象,所有的js函数,变量等都是window对象成员

甚至Dom的document也是window对象的属性之一

1.1.1 三种弹出框

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>三种弹出框</title>
	</head>
	<body>
		
		<script>
			
			// 警告框
			alert("Hello");
			
			// 确认框
			var bl = confirm("你确定要删除吗?");
			console.log(bl);
			
			// 输入框--接受的内容类型为String
			var str = prompt("请输入内容");
			console.log(str);
			console.log(typeof(str));
			
			
		</script>
	</body>
</html>

1.1.2 定时器

clearInterval()

取消由setInterval()设置的timeout

clearTimeout()

取消setTimeout()设置的timeout

setInterval()

按照指定的周期(以毫秒计)来调用函数或计算表达式。

setTimeout()

在指定的毫秒数后调用函数或计算表达式。

案例:让时间走动,进行开始或者停止控制

<script>

  //设置一个时间周期,参数1:表示是一个调用的方法,参数2:表示的时间周期
  var interval_id = window.setInterval("_setTime()",1000);

  //页面一刷新,用户就可以看到时间,但是这个是静态的
  window.onload = function(){
    //获取id
    var _time = document.getElementById("_time");

    //获取当前时间
    var date = new Date();

    //把时间写入到span标签中
    _time.innerHTML = date.toLocaleString();
  }

  function _setTime(){
    //获取id
    var _time = document.getElementById("_time");

    //获取当前时间
    var date = new Date();

    //把时间写入到span标签中
    _time.innerHTML = date.toLocaleString();
  }

  //停止时间
  function _stopTime(){
    window.clearInterval(interval_id);//获取设置时间周期的id
  }
  //开始时间
  function _stratTime(){
    interval_id = window.setInterval("_setTime()",1000);
  }

</script>
</head>
<body>
  <span style="color: red;" id="_time"></span>
  <input type="button" value="停止时间" onclick="_stopTime()"/>
  <input type="button" value="开始时间" onclick="_stratTime()"/>
</body>

倒记时案例

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">

    <!-- html中有一个meta标签,可以实现页面刷新,可以看作是倒记时 -->
    <meta http-equiv="refresh" content="10;url=https://www.baidu.com">
    <title></title>

    <!-- 通过js配合meta标签,把这个倒记时的时间,显示给用户,效果是时间递减 -->
    <script>
      var time = 10;
      window.onload = function(){
        window.setInterval("setTime()",1000);
      }
      function setTime(){
        document.getElementById("spanid").innerHTML = time;
        time--;
      }
    </script>

  </head>
  <body>

    <center>
      <span style="font-size: 78px; color:orange; text-align: center;"  id="spanid"></span>
      秒后跳转到<a href="https://www.baidu.com"> 百度</a>
    </center>
    <div align="center">
      <img src="img/404.jpg" />
    </div>

  </body>
</html>

1.1.3 关闭,打开浏览器

close()

关闭浏览器

open()

打开浏览器

1.2 history对象

history对象包含用户访问过的url,  注意: 一定是访问过的历史url

history是window对象的一部份,可以通过window.history属性进行访问

demo04--history对象.html

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>History对象01</title>
    <script>
      function after(){
        history.forward();
      }
    </script>
  </head>
  <body>
    <a href="demo05--history对象.html">第二页</a>
    <button onclick="after()">下一页</button>
  </body>
</html>

demo05--history对象.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>History对象02</title>
    <script>
      function before(){
        history.back();
      }
      function after(){
        history.forward();
      }

      // history.go(1)  :是返回到上一页
      // history.go(-1) :是返回到下一页
      // history.go(0)  :是刷新页面
    </script>
  </head>
  <body>
    <a href="demo06--history对象.html">第三页</a>
    <button onclick="before()">上一页</button>
    <button onclick="after()">下一页</button>
  </body>
</html>

demo06--history对象.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>History对象03</title>
    <script>
      function before(){
        history.back();
      }
    </script>
  </head>
  <body>
    <a href="demo04--history对象.html">第一页</a>
    <button onclick="before()">上一页</button>
  </body>
</html>

1.3 Location对象

Location对象是window对象的一部份,可以通过window.location属性来访问

location表示是当前浏览器的地址对象。浏览器的地址中主要保存的是访问某个网站的url地址

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>location对象</title>

    <script>
      function baidu(){
        location.assign("http://www.baidu.com");
      }

      function sina(){
        location.replace("http://www.sina.com.cn");
      }
    </script>
  </head>
  <body>
    <button onclick="baidu()">百度</button>
    <button onclick="sina()">新浪</button>
  </body>
</html>

2、Dom对象

Dom对象: Document Object Model  文档对象模型

W3C组织规定:

        当浏览器把一个html文件加载到内存中之后,这个html文件,就是一个Document对象。并且在浏览器加载html文件中的所有标签时,把html文件中的所有标签页加载成不同的标签对象,以及标签中的属性,也加载成属性对象,标签中的文本也加载成文本对象。

        浏览器在加载某个标签时,标签的文本数据,被加载成当前标签的一个子标签。当我们把一个html文件加载完成之后,他们就得到这个html文件中的所有标签,属性,文本对象。可以使用js技术结合Document对象,对html文件中的所有标签,进行各种操作。

        在浏览器把html文件加载完成之后,标签被称作标签对象(元素节点),标签中的文件称为文本节点(文本对象),标签的属性称为属性节点(属性对象)。

2.1 document对象

Document对象代表整个html文档,可用来访问页面中的所有元素,快速获取html中的页面的标签对象

document.getElementById()

返回指定id对象的引用

document.getElementsByName()

返回指定带有名称的对象集合

document.getElementsTagName()

返回指定带有标签名的对象集合

document.getElementsByClassName()

根据Class属性值获取元素对象们。返回值是一个数组

document.querySelector(id选择器)

根据id选择器,获取元素

document.querySelectorAll(css选择器)

根据css选择器获取元素,返回是一个数组

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Document对象</title>
    <script>

      window.onload = function(){
        // getElementById();
        console.log(document.getElementById("nav").innerText);

        // querySelector()
        console.log(document.querySelector("#nav").innerText);

        // getElementsByTagNam()
        var aArray = document.getElementsByTagName("a");
        console.log(aArray)
        for (var s of aArray) {
          console.log(s.innerText)
        }

        // getElementsByName()
        var hobbies = document.getElementsByName("hobby");
        console.log(hobbies)
        for (var s of hobbies) {
          console.log(s.value)
        }

        // getElementsByClassName()
        var cls1 = document.getElementsByClassName("d1");
        console.log(cls1)
        for (var s of cls1) {
          console.log(s.innerText)
        }

        // querySelectorAll(".hd1") css选择器
        var cls2 = document.querySelectorAll(".d1");
        console.log(cls2)
        for (var s of cls2) {
          console.log(s.innerText)
        }

      }
    </script>

  </head>
  <body>
    <div id="nav" class="d1">
      111
    </div>
    <a href="#" class="d1">链接1</a>
    <a href="#">链接2</a>

    <input type="checkbox" name="hobby" value="sing">唱歌
    <input type="checkbox" name="hobby" value="dance">跳舞
    <input type="checkbox" name="hobby" value="rap">rap
  </body>
</html>

2.2 操作内容

属性名

描述

element.innerText

获取或者修改元素的纯文本内容

element.innerHTML

获取或者修改元素的html内容

element.outerHTML

获取或者修改包含自身的html内容

1. innerText 获取的是纯文本 innerHTML获取的是所有html内容

2. innerText 设置到页面中的是纯文本 innerHTML设置到页面中的html会展示出外观效果

3. innerHTML不包含自身 outerHTML包含自身的html内容

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <style>
            #myDiv {
                border: 1px solid red;
            }
        </style>
    </head>
    <body>
        <div id="myDiv">
			<h4>注释</h4>
			程序猿最讨厌自己写注释,
			同时也最讨厌别人不写注释
		</div>

        <script>
			//获取id
            let myDiv = document.getElementById('myDiv');
			
			//innerHTML 获取标签中所有内容,包括标签;从对象的起始位置到终止位置的全部内容
			console.info(myDiv.innerHTML);
			console.info(myDiv.innerHTML="拉出去");
			console.info(myDiv.innerHTML+="拉出去");
			
			// innerText 获取标签中纯文本内容,不包括标签;
			console.info(myDiv.innerText);
			console.info(myDiv.innerText="拉出去");
			console.info(myDiv.innerText+="拉出去");
			
			// outerHTML 获取标签本身,修改标签本身 ,添加标签本身的后面
			console.info(myDiv.outerHTML);
			console.info(myDiv.outerHTML="<h1>别人从不写注释,不写文档... </h1>");
			console.info(myDiv.outerHTML +="<h1>别人从不写注释,不写文档... </h1>");
			
        </script>
	</body>
</html>

2.3 操作节点

createElement(标签名称)

创建标签

appendChild

为某一个标签,去添加子标签

removeChild

为某一个标签,删除孩子标签

setAttribute

为某一个标签添属性

removeAttribute

删除某一个标签中的属性

2.3.1 appendChild添加子标签

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>添加子标签--appendChild</title>
  </head>
  <body>
    <ul id="uls">
      <li>jack</li>
      <li>rose</li>
    </ul>

    <input type="button" onclick="addElement()"  value="添加子标签" />


    <script>
      function addElement(){
        // 创建标签
        var lis = document.createElement("li");//<li></li>

        // 给标签中添加内容
        lis.innerText = "tom";

        //添加到父标签中
        document.getElementById("uls").appendChild(lis);
      }
    </script>
  </body>
</html>

2.3.2 removeChild删除子标签

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>删除子标签--removeChild</title>
	</head>
	<body>
		<ul id="uls">
			<li>jack</li>
			<li id="x1">rose</li>
			<li>tom</li>
			<li>mary</li>
		</ul>
				
		<input type="button" onclick="deleteOne()" value="删除子标签" />
		<input type="button" onclick="deleteAll()" value="删除全部标签" />
		<input type="button" onclick="deleteOneByOne()"  value="依次删除子标签" />
		
		<script>
			// 删除指定子标签
			function deleteOne(){
				// 找到要删除的指定子标签
				var li = document.getElementById("x1");
				
				// 删除子标签
				li.parentNode.removeChild(li);
			}
			
			// 删除全部子标签
			function deleteAll(){
				// 获取父元素标签
				var uls = document.getElementById("uls");
				
				// 根据父元素获取所有的子元素标签
				var childs = uls.childNodes;
				
				//删除全部,必从后往前遍历,否则无法删除全部
				for(var i = childs.length - 1; i >= 0; i--){
					uls.removeChild(childs[i]);
				}
			}
			
			// 依次删除子标签
			function deleteOneByOne(){
				// 获取全部的li元素标签
				var lis = document.getElementsByTagName("li");
				
				// 获取第一个li元素标签
				var li = lis[0];
				
				// 删除第一个元素标签
				li.parentNode.removeChild(li);
				
			}
		</script>
	</body>
</html>

2.3.3 setAttribute添加属性

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>添加属性--setAttribute</title>
  </head>
  <body>
    <input type="text" name="username"  autocomplete="off">
    <input type="text" name="username">
    <input type="text" name="username">
    <input type="text" name="username">
    <input type="text" name="username">

    <script>
      window.onload = function(){
        //给所有input添加 autocomplete="off"
        var tagName = document.getElementsByTagName("input");
        for (var i = 0; i < tagName.length; i++) {
          tagName[i].setAttribute("autocomplete","off");
        }
      }
    </script>
  </body>
</html>

2.3.4 removeAttribute删除属性

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>删除属性--removeAttribute</title>
  </head>
  <body>

    <input type="text" name="username"  autocomplete="off">
    <input type="text" name="username">
    <input type="text" name="username">
    <input type="text" name="username">
    <input type="text" name="username">

    <script>
      window.onload = function(){
        //给所有input添加 autocomplete="off"
        var tagName = document.getElementsByTagName("input");
        //遍历
        for (var i = 0; i < tagName.length; i++) {
          //移除input框中所有name属性
          tagName[i].removeAttribute("name");
        }
      }
    </script>
  </body>
</html>

2.4 操作样式

设置一个css样式

js对象.style.样式名='样式值'

批量设置css样式-了解

js对象.style.cssText='属性名:属性值;...'

通过class设置样式【重点】

js对象.className='样式名称1; 样式名称2;...'

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>操作样式</title>
		<style>
		    .mpp {
				background-color: orange;
		    }
		</style>
	</head>
	<body>
		
		<p id="p1">1. 设置一个css样式</p>
		<p id="p2">2. 批量设置css样式</p>
		<p id="p3">3. 通过class设置样式</p>
		
		<script>
			// 1. 设置一个css样式
			// 设置字体大小
			p1.style.fontSize = "20px";
			// 设置背景颜色
			p1.style.backgroundColor = "green";
			// 设置字体颜色
			p1.style.color = "red";
			
			// 2. 批量设置css样式
			// 缺点:写起来太痛苦,而且还有耦合性
			p2.style.cssText = "border:2px solid red; font-size:40px";
			
			// 3. 通过class设置样式
			p3.className = "mpp";
		</script>
			
	</body>
</html>

案例

案例1 表单验证

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>注册页面</title>
		<style>
			*{
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}
			body{
				background-image: url(./img/bg-01.jpg);
				background-repeat: no-repeat;
				background-size: cover;
			}
			.nav{
				height: 300px;
				width: 500px;
				/* background-color: white; */
				font-size: 20px;
				color: white;
				margin: 200px auto;
				padding-top: 10px;
			}
			.nav .btn{
				height: 40px;
				width: 100px;
				font-size: 16px;
				text-align: center;
				line-height: 40px;
				border-radius: 15px;
				margin: 10px 220px;
			}
			table tr{
				height: 40px;
				line-height: 40px;
			}
			.in{
				height: 30px;
				width: 280px;
				text-indent: 5px;
				font-size: 15px;
			}
		</style>
	</head>
	<body>
		<div class="nav">
			<form action="#" onsubmit="return isSubmit()">
				<table width="500px">
					<tr>
						<td width="200px" align="right">用户名:</td>
						<td>
							<input type="text" class="in" placeholder="用户名是以字母开头的3-8位的任意字符" onchange="getUsername(this)" name="username"/>
							<span id="userMess"></span>
						</td>
					</tr>
					<tr>
						<td align="right">密码:</td>
						<td>
							<input type="password" class="in" placeholder="密码由8-16位的字母或数字组成" onchange="getPassword(this)" name="password"/>
							<span id="pwdMess"></span>
						</td>
					</tr>
					<tr>
						<td align="right">手机号:</td>
						<td>
							<input type="tel" class="in" placeholder="请输入手机号" onchange="getPhone(this)" name="phone"/>
							<span id="telMess"></span>
						</td>
					</tr>
					<tr>
						<td align="right">性别:</td>
						<td>
							<input type="radio" name="sex" value="1" checked id="man"/><label for="man">男</label>
							<input type="radio" name="sex" value="0" id="woman"/><label for="woman">女</label>
						</td>
					</tr>
					<tr>
						<td align="right">爱好:</td>
						<td>
							<input type="checkbox" name="hobby" id="music" checked value="music"/><label for="music">听音乐</label>
							<input type="checkbox" name="hobby" id="noval" value="noval"/><label for="noval">看小说</label>
							<input type="checkbox" name="hobby" id="player" value="player"/><label for="player">追剧</label>
						</td>
					</tr>
					<tr>
						<td colspan="2">
							<input type="submit" value="注册" class="btn" id="btn"/>
						</td>
					</tr>
				</table>
			</form>
			
		</div>
		
		
		<script>
			let flag1 = false;
			let flag2 = false;
			let flag3 = false;
			function getUsername(e){
				console.log(e.value)
				let username = e.value;
				// 用户名是以字母开头的3-8位的任意字符
				var reg = /^[a-zA-Z].{2,7}$/;
				// if(!reg.test(username)){
				// 	alert("用户名是以字母开头的3-8位的任意字符");
				// 	// 用户输错时,清除输入框
				// 	e.value = "";
				// }
				// var flag = false;
				if(reg.test(username)){
					document.getElementById("userMess").innerHTML = "<font color = 'green'>✔</font>";
					flag1 = true;
				} else {
					document.getElementById("userMess").innerHTML = "<font color = 'red'>✘</font>";
					flag1 = false;
				}
			}
			function getPassword(e){
				console.log(e.value);
				let password = e.value;
				// 密码由8-16位的字母或数字组成
				var reg = /^[a-zA-Z0-9]{8,16}$/;
				// if(!reg.test(password)){
				// 	alert("密码由8-16位的字母或数字组成");
				// 	e.value = "";
				// }
				// var flag = false;
				if(reg.test(password)){
					document.getElementById("pwdMess").innerHTML = "<font color = 'green'>✔</font>";
					flag2 = true;
				} else {
					document.getElementById("pwdMess").innerHTML = "<font color = 'red'>✘</font>";
					flag2 = false;
				}
			}
			function getPhone(e){
				console.log(e.value);
				let phone = e.value;
				// 手机号由11为纯数字且首字母为1且第二位不为0
				var reg = /^[1][1-9][0-9]{9}$/;
				// if(!reg.test(phone)){
				// 	alert("你输入的手机号不正确,请重新输入");
				// 	e.value = "";
				// }
				// var flag = false;
				if(reg.test(phone)){
					document.getElementById("telMess").innerHTML = "<font color = 'green'>✔</font>";
					flag3 = true;
				} else {
					document.getElementById("telMess").innerHTML = "<font color = 'red'>✘</font>";
					flag3 = false;
				}
			}
			
			function isSubmit(){
				if (flag1 && flag2 && flag3){
					return true;
				}else{
					return false;
				}
			}
		</script>
	</body>
</html>

案例2:全选全不选

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>全选全不选</title>
	</head>
	<body>
		<input type="checkbox" id="input" onclick="checkAll()" />全选/全不选<br />
		<input type="checkbox" name="hobby" value="足球" />足球<br />
		<input type="checkbox" name="hobby" value="篮球" />篮球<br />
		<input type="checkbox" name="hobby" value="游泳" />游泳<br />
		<input type="checkbox" name="hobby" value="唱歌" />唱歌<br />
		<br />
		<input type="button" name="checkall" id="checkall" value="全选"/>
		<input type="button" name="checkall" id="checkallNo" value="全不选" onclick="checkAllNo()"/>
		<input type="button" name="checkall" id="checkReverse" value="反选" onclick="checkReverse()"/>
		
		
		<script>
			// 全选
			window.onload = function(){
				// 页面加载完毕,获取全选按钮
				var checkall = document.getElementById("checkall");
				checkall.onclick = function(){
					// 根据name属性获取所有的复选框
					var hobbies = document.getElementsByName("hobby");
					// 遍历数组
					for (var i = 0; i < hobbies.length; i++) {
						// 为每个复选框的checked属性设置true,表示选中状态
						hobbies[i].checked = true;
					}
				}
			}
			
			// 全不选
			function checkAllNo(){
				// 根据name属性获取所有的复选框
				var hobbies = document.getElementsByName("hobby");
				// 遍历数组
				for (var i = 0; i < hobbies.length; i++) {
					// 为每个复选框的checked属性设置true,表示选中状态
					hobbies[i].checked = false;
				}
			}
			
			// 反选
			function checkReverse(){
				// 根据name属性获取所有的复选框
				var hobbies = document.getElementsByName("hobby");
				// 遍历数组
				for (var i = 0; i < hobbies.length; i++) {
					// 如果为hobbies[i]true修改为false,如果为false修改为true
					/* if(hobbies[i].checked == true){
						hobbies[i].checked = false
					}else{
						hobbies[i].checked = true
					} */
					hobbies[i].checked = !hobbies[i].checked
				}
			}
			
			// 全选/全不选
			function checkAll(){
				var btn = document.getElementById("input");
				// 根据name属性获取所有的复选框
				var hobbies = document.getElementsByName("hobby");
				// 遍历数组
				for (var i = 0; i < hobbies.length; i++) {
					// 如果为hobbies[i]true修改为false,如果为false修改为true
					/* if(btn.checked == true){
						hobbies[i].checked = true
					}else{
						hobbies[i].checked = false
					} */
					hobbies[i].checked = btn.checked
				}
			}
		</script>
	</body>
</html>
  • 25
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

憨憨浩浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值