JavaScript review Dom&Bom

One, the dom object in Javascript

1. Control events

  1. Button click event onclick

      Specific usage:

            <script>

                  function Click event processing function () {

                        //Event handling action

                  }

            </script>

            <input type=”button” value=”button” οnclick=”handling function after button click”/>

  2. Page initialization event onload

      Specific usage:

            <script>

                  function processing function () {

                        //Event handling action

                  }

            </script>

            <body οnlοad="Processing function"></body>

  3. Common javascript events, specific usage methods of events

       1. Page initialization event

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			function  testOnload(){
				alert("页面初始化事件");
			}
		</script>
	</head>
	<body  onload="testOnload();">
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			//通过window对象调用onload事件
			window.onload=function(){
				alert("页面初始化事件");
			}
		</script>
	</head>
	<body>
	</body>
</html>

       2. Button click event onclick

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			function  testClick(){
				alert("按钮点击事件");
			}
		</script>
	</head>
	<body>
		<input type="button" value="测试按钮点击事件" onclick="testClick();"/>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			window.onload=function(){
				var  but1=document.getElementById("but1");//object HTMLInputElement
				but1.onclick=function(){
					alert("按钮点击事件2");
				}
			}
		</script>
	</head>
	<body>
		<input id="but1" type="button" value="测试按钮点击事件2" />
	</body>
</html>

       3. The onchange event, which is triggered when the user changes the content of the input field

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			function  testonchange(){
				alert("输入内容被改变是触发");
			}
		</script>
	</head>
	<body>
		<input type="text"  value="hello" onchange="testonchange();" />
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			window.onload=function(){
				var text1=document.getElementById("text1");
				text1.onchange=function(){
					alert("输入内容被改变是触发2");
				}
			}
		</script>
	</head>
	<body>
		<input id="text1" type="text"  value="hello"  />
	</body>
</html>

       4.onfocus is triggered when the focus is obtained

       5.onblur triggers when the focus is lost

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
	<script>
	    function  testonfocus(){
	        var text1=document.getElementById("text1");
		    text1.value="";
		}	
	    window.onload=function(){
                var text1=document.getElementById("text1");
		text1.onblur=function(){
		    var reg1=new RegExp(/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/);
		    var val=text1.value;
		    var boo=reg1.test(val);
		    if(boo){
		        alert("手机号码正确,获取短息验证码");
		    }else{
		        alert("手机号码不正确,请重新输入");
		    }
	        }
	    }
        </script>
    </head>
    <body>
        <input id="text1" type="text"  value="请输入手机号码" onfocus="testonfocus();" /><br>
    </body>
</html>

       6. onmouseover and onmouseout events

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			window.onload=function(){
				var img1=document.getElementById("img1");
				img1.onmouseover=function(){
					img1.style.width="250px";
					img1.style.height="250px";
				}
				img1.onmouseout=function(){
					img1.style.width="150px";
					img1.style.height="150px";
				}
			}
		</script>
	</head>
	<body>
		<img id="img1" src="imgs/avatar.png" />
	</body>
</html>

       7. The onsubmit event will occur when the confirmation button [submit] in the form is clicked.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			//1.普通按钮type="button",无法触发表单提交事件onsubmit
			//2.onsubmit事件对应的处理函数一定要有返回值【boolean】
			//true---提交表单数据
			//false---不提交表单数据
			//3.表单的onsubmit="return 处理函数";
			function  testOnsubmit(){
				var text1=document.getElementById("text1");
				var pass1=document.getElementById("pass1");
				var span1=document.getElementById("span1");
				var username=text1.value;
				var password=pass1.value;
				if(username=="zhangsan" && password=="123456"){
					alert("登陆成功!");
					return true;
				}else{
					span1.innerHTML="<font color='red' size='7'>用户名密码错误!</font>";
					return false;
				}
			}
		</script>
	</head>
	<body>
		<span id="span1"></span>
		<form action="#" method="get" onsubmit="return  testOnsubmit();">
			用户名:<input id="text1" name="username" type="text" /><br>
			密码:<input id="pass1" name="password"  type="password" /><br>
			<input type="button" value="普通按钮" /><br>
			<input type="submit" value="登陆" />
		</form>
	</body>
</html>

       8. The onkeydown event occurs when the user presses a keyboard key.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			//1.testKeydown事件在调用的时候需要一个event参数
			//2.event参数的keyCode属性得到键盘按键对应的数字。
			function testKeydown(event){
				var num=event.keyCode;
				if(num==65 || num==37){
					alert("向左移动");
				}
				if(num==68 || num==39){
					alert("向右移动");
				}
				if(num==87 || num==38){
					alert("向上移动");
				}
				if(num==83 || num==40){
					alert("向下移动");
				}
				if(num==13){
					alert("暂停");
				}
			}
		</script>
	</head>
	<body onkeydown="testKeydown(event);">
	</body>
</html>

https://www.w3school.com.cn/jsref/dom_obj_event.asp

onabort

The loading of the image was interrupted.

onblur

The element loses focus.

onchange

The content of the domain is changed.

onclick

The event handler that is called when the user clicks on an object.

ondblclick

The event handler that is called when the user double-clicks an object.

onerror

An error occurred while loading the document or image.

onfocus

The element gains focus.

onkeydown

A keyboard key was pressed.

onkeypress

A keyboard key was pressed and released.

onkeyup

A keyboard key was released.

onload

A page or an image is loaded.

onmousedown

The mouse button is pressed.

onmousemove

The mouse is moved.

onmouseout

Move the mouse away from an element.

onmouseover

Move the mouse over an element.

onmouseup

The mouse button is released.

onreset

The reset button was clicked.

onresize

The window or frame is resized.

onselect

The text is selected.

onsubmit

The confirmation button is clicked.

onunload

The user exits the page.

Create a new HTML element  

document. createElement ("Element Name");

document. createTextNode ("Text Content");

 

The dom object of the parent element. appendChild (node);

Delete elements of the parent element dom objects . RemoveChild ( child element of dom objects );

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			div{
				width: 300px;
				height: 300px;
				background-color: red;
			}
		</style>
		<script>
			window.onload=function(){
				var addbut=document.getElementById("add");
				var deletebut=document.getElementById("delete");
				addbut.onclick=function(){
					//创建元素
					var hdom=document.createElement("h1");
					var htext=document.createTextNode("这是我添加的一个元素");
					hdom.appendChild(htext);
					var divdom=document.getElementById("div1");
					divdom.appendChild(hdom);
				}
				deletebut.onclick=function(){
					var divdom=document.getElementById("div1");
					var hdom=document.getElementById("h1");
					//删除元素
					divdom.removeChild(hdom);
				}
			}
		</script>
	</head>
	<body>
		<div id="div1">
			<h1 id="h1">测试添加和移除元素</h1>
		</div>
		<input id="add" type="button" value="添加元素"><br>
		<input id="delete" type="button" value="删除元素"><br>
	</body>
</html>

Second, the BOM object in JavaScript

   Browser Object Model (BOM)

   Window object

    Attributes

        There are three ways to determine the size of the browser window (viewport of the browser, excluding toolbars and scroll bars).

        For Internet Explorer, Chrome, Firefox, Opera and Safari:

        window.innerHeight-the inner height of the browser window

        window.innerWidth-the inner width of the browser window

        For Internet Explorer 8, 7, 6, 5:

        document.documentElement.clientHeight

        document.documentElement.clientWidth

        or

        document.body.clientHeight

        document.body.clientWidth

        Practical JavaScript solutions (covering all browsers):

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			window.onload=function(){
				//确定浏览器窗口的尺寸(浏览器的视口,不包括工具栏和滚动条)
				var w=window.innerWidth || 
					  document.documentElement.clientWidth || 
					  document.body.clientWidth;
				var h=window.innerHeight || 
				      document.documentElement.clientHeight ||
					  document.body.clientHeight;
				window.alert(w+"*"+h);	  
			}
		</script>
	</head>
	<body>
	</body>
</html>

     method

       Other methods: The open() method is used to open a new browser window or find a named window

                 格式:window.open(URL,name,features,replace)

URL

An optional string that declares the URL of the document to be displayed in the new window. If this parameter is omitted, or its value is an empty string, then no document will be displayed in the new window.

name

An optional string that is a comma-separated list of features, including numbers, letters, and underscores, which declare the name of the new window. This name can be used as the value of the target attribute of the tags <a> and <form>. If this parameter specifies an existing window, then the open() method does not create a new window, but just returns a reference to the specified window. In this case, features will be ignored.

features

An optional string that declares the characteristics of the standard browser to be displayed in the new window. If this parameter is omitted, the new window will have all standard features.

replace

An optional Boolean value. Specifies whether the URL loaded into the window will create a new entry in the browsing history of the window or replace the current entry in the browsing history. The following values ​​are supported:

true-URL replaces the current entry in the browsing history.

false-URL creates a new entry in the browsing history.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			function open_win(){
				window.open("https://www.baidu.com/");
			}
			function open_aboutblank(){
				window.open("about:blank","空白页","width=200,height=100",false);
			}
		</script>
	</head>
	<body>
		<input type=button value="Open百度" onclick="open_win()" /><br>
		<input type=button value="about:blank" onclick="open_aboutblank()" />
	</body>
</html>

       Important: Please do not confuse the method Window.open() with the method Document.open(), the functions of the two are completely different. In order to make your code clear, please use Window.open() instead of open().                

      The close() method is used to close the browser window.

      说明:方法 close() 将关闭有 window 指定的顶层浏览器窗口。某个窗口可以通过调用 self.close() 或只调用 close() 来关闭其自身。

      只有通过 JavaScript 代码打开的窗口才能够由 JavaScript 代码关闭。这阻止了恶意的脚本终止用户的浏览器。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			var myWindow=null;
			
			window.onload=function(){
				myWindow=window.open("about:blank","","width=200,height=100");
				myWindow.document.write("This is 'myWindow'");
			}
			
			function closeWin(){
				myWindow.close();
			}
		</script>
	</head>
	<body>
		<input type="button" value="Close 'myWindow'"
		onclick="closeWin()" />
	</body>
</html>

      JavaScript 弹窗方法

            在 JavaScript 中创建三种消息框:警告框、确认框、提示框。

            警告框:window.alert("sometext");

            确认框:window.confirm("sometext");

            当确认卡弹出时,用户可以点击 "确认" 或者 "取消" 来确定用户操作。

            当你点击 "确认", 确认框返回 true, 如果点击 "取消", 确认框返回 false。

            提示框:window.prompt("sometext","defaultvalue");

            当提示框出现后,用户需要输入某个值,然后点击确认或取消按钮才能继续操纵。

            如果用户点击确认,那么返回值为输入的值。如果用户点击取消,那么返回值为 null。

            参数1---提示信息

            参数2---提示框的默认值

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#div1{
				width: 300px;
				height: 300px;
				background-color: red;
			}
		</style>
		<script>
			window.onload=function(){
				var butObj=document.getElementById("but1");
				butObj.onclick=function(){
					//window.alert("测试警告框");
					var val=window.confirm("确定要删除吗?");
					if(val){
						var divObj=document.getElementById("div1");
						var hObj=document.getElementById("h");
						divObj.removeChild(hObj);
					}
				}
				
				var butObj2=document.getElementById("but2");
				butObj2.onclick=function(){
					var val=window.prompt("请输入姓名","");
					if(val.length>0){
						alert(val);
					}else{
						alert("不能为空!");
					}
				}
				
			}
		</script>
	</head>
	<body>
		<div id="div1">
			<h1 id="h">测试确认框</h1>
		</div>
		<input id="but1" type="button" value="删除H1" /><br>
		<input id="but2" type="button" value="测试提示框" />
	</body>
</html>

     子对象

         1.Window Screen--屏幕

           window.screen 对象包含有关用户屏幕的信息。

           1.总宽度和总高度  --- screen.width   /  screen.height

           2.可用宽度和可用高度----screen.availWidth  / screen.availHeight

           3.色彩深度----screen.colorDepth

           4.色彩分辨率----screen.pixelDepth

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			//1.总宽度和总高度  --- screen.width   /  screen.height
			window.document.write("<h1>总宽度和总高度:"+window.screen.width+
			"*"+window.screen.height+"</h1>");
			//2.可用宽度和可用高度----screen.availWidth  / screen.availHeight
			window.document.write("<h1>可用宽度和可用高度:"+window.screen.availWidth+
			"*"+window.screen.availHeight+"</h1>");
			//3.色彩深度----screen.colorDepth
			window.document.write("<h1>色彩深度:"+window.screen.colorDepth+"</h1>");
			//3.色彩分辨率----screen.pixelDepth
			window.document.write("<h1>色彩分辨率:"+window.screen.colorDepth+"</h1>");
		</script>
	</head>
	<body>
	</body>
</html>

         2.Window Location---页面的地址 (URL)

               对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。

               location.href 属性返回当前页面的 URL。

               location.search 属性是一个可读可写的字符串,可设置或返回当前 URL 的查询部分(问号 ? 之后的部分)。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			document.write("<h1>href:"+window.location.href+"</h1>");
			document.write("<h1>pathname :"+window.location.pathname +"</h1>");
			document.write("<h1>search :"+window.location.search+"</h1>");
		</script>
	</head>
	<body>
	</body>
</html>

实例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>用户登录</title>
		<script>
			window.onload=function(){
				var but1=document.getElementById("but1");
				var username=document.getElementById("text1");
				var password=document.getElementById("pass1");
				var span=document.getElementById("span");
				but1.onclick=function(){
					var usernamevalue=username.value;
					var passwordvalue=password.value;
					if(usernamevalue=="zhangsan" && passwordvalue=="123456"){
						//跳转到成功的页面,传递用户名
						window.location.href="success.html?username="+usernamevalue;
					}else{
						//给出错误提示
						span.innerHTML="<font color='red'>用户名密码错误!</font>";
					}
				}
				//为用户名输入框添加聚焦事件
				username.onfocus=function(){
					span.innerHTML="";
					username.value="";
					password.value="";
				}
			}
		</script>
	</head>
	<body>
		<center>
		<table border="1px">
			<tr align="center">
				<td colspan="2">
					<h1>用户登录</h1>
					<span id="span"></span>
				</td>
			</tr>
			<tr align="center">
				<td>用户名:</td>
				<td><input id="text1" type="text" name="username"></td>
			</tr>
			<tr align="center">
				<td>密码:</td>
				<td><input id="pass1" type="password" name="password"></td>
			</tr>
			<tr align="center">
				<td colspan="2"><input id="but1" type="button" value="用户登录" /></td>
			</tr>
		</table>
		</center>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			window.onload=function(){
				var searchvalue=window.location.search;
				if(searchvalue.length<=0){
					window.location.href="login.html";
				}else{
				    //searchvalue===?username=zhangsan
					//var strarray=searchvalue.split("=");
					//var username=strarray[1];
					var username=searchvalue.split("=")[1];
					var h1obj=document.getElementById("h1");
					h1obj.innerHTML="欢迎,"+username+"登录成功!";
				}
			}
		</script>
	</head>
	<body>
		<center>
			<h1 id="h1">欢迎,登录成功!</h1>
		</center>
	</body>
</html>

         3.Window History---历史对象

              window.history 对象包含浏览器的历史信息。

              history.back() - 与在浏览器点击后退按钮相同

              history.forward() - 与在浏览器中点击按钮向前相同

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
				//前进
				function toNext(){
					window.history.forward();
				}
		</script>
	</head>
	<body>
		<h1>第一个测试页面</h1>
		<a href="test1.html">连接到第一个测试页面</a><br>
		<input type="button" value="前进" onclick="toNext();"/>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
				//前进
				function toNext(){
					window.history.forward();
				}
				//后退
				function toBack(){
					window.history.back();
				}
		</script>
	</head>
	<body>
		<h1>第二个测试页面</h1>
		<a href="test2.html">连接到第三个测试页面</a><br>
		<input type="button" value="前进" onclick="toNext();"/>
		<input type="button" value="后退" onclick="toBack();"/>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
				//后退
				function toBack(){
					window.history.back();
				}
		</script>
	</head>
	<body>
		<h1>第三个测试页面</h1>
		<input type="button" value="后退" onclick="toBack();"/>
	</body>
</html>

注意:前进history.forward()和后退history.back()在同一个窗口中的页面才有效。

         4.Window Navigator--浏览器的信息

              window.navigator 对象包含有关访问者浏览器的信息。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
		document.write("<h1>浏览器代号:"+window.navigator.appCodeName+"</h1>");
		document.write("<h1>浏览器名称:"+window.navigator.appName+"</h1>");
		document.write("<h1>浏览器版本:"+window.navigator.appVersion+"</h1>");
		document.write("<h1>启用Cookies:"+window.navigator.cookieEnabled+"</h1>");
		document.write("<h1>硬件平台:"+window.navigator.platform+"</h1>");
		document.write("<h1>用户代理:"+window.navigator.userAgent+"</h1>");
		document.write("<h1>用户代理语言:"+window.navigator.systemLanguage+"</h1>");
		</script>
	</head>
	<body>
	</body>
</html>

         JavaScript 计时事件

               通过使用 JavaScript,我们有能力作到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。

               在 JavaScritp 中使用计时事件是很容易的,两个关键方法是:

               setInterval() - 间隔指定的毫秒数不停地执行指定的代码。

               setTimeout() -  暂停指定的毫秒数后执行指定的代码

               setInterval() 和 setTimeout() 是 HTML DOM Window对象的两个方法。

               setInterval() 方法

               setInterval(“function”,milliseconds) 间隔指定的毫秒数不停地执行指定的代码。

               参数1-指定的运行代码是一个function

               参数2-指定的毫秒数

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			function testsetInterval(){
				var hobj=document.getElementById("test1");
				setInterval(function(){
					var date=new Date();
					var year=date.getFullYear();
					var month=date.getMonth()+1;
					var mydate=date.getDate();
					var hours=date.getHours()
					var minutes=date.getMinutes();
					var seconds=date.getSeconds();
					var time=year+"年"+month+"月"+mydate+"日 "+hours+":"+minutes+":"+seconds;
					hobj.innerHTML=time;
				},1000);
			}
		</script>
	</head>
	<body>
		<h1 id="test1"></h1>
		<input type="button" value="测试setInterval()————1" onclick="testsetInterval();"/>
	</body>
</html>

      将setInerval()方法中执行运行的代码抽取成一个函数。


function testsetInterval(){
    var hobj=document.getElementById("test1");
    function mygetDate(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var mydate=date.getDate();
        var hours=date.getHours()
        var minutes=date.getMinutes();
        var seconds=date.getSeconds();
        var time=year+"年"+month+"月"+mydate+"日 "+hours+":"+minutes+":"+seconds;
        hobj.innerHTML=time;
    }
    setInterval(function(){mygetDate();},1000);
}

        clearInterval(intervalVariable) 方法用于停止 setInterval() 方法执行的函数代码。

        参数intervalVariable--- setInterval()的返回值。

例如:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			var mysetinterval=null;
			function testsetInterval(){
				var hobj=document.getElementById("test1");
				function mygetDate(){
					var date=new Date();
					var year=date.getFullYear();
					var month=date.getMonth()+1;
					var mydate=date.getDate();
					var hours=date.getHours()
					var minutes=date.getMinutes();
					var seconds=date.getSeconds();
					var time=year+"年"+month+"月"+mydate+"日 "+hours+":"+minutes+":"+seconds;
					hobj.innerHTML=time;
				}
				mysetinterval=setInterval(function(){mygetDate();},1000);
			}
			//停止setInterval
			function  testclearInterval(){
				clearInterval(mysetinterval);
			}
		</script>
	</head>
	<body>
		<h1 id="test1"></h1>
		<input type="button" value="测试setInterval()" onclick="testsetInterval();"/>
		<input type="button" value="停止setInterval()" onclick="testclearInterval();"/>
	</body>
</html>

      setTimeout() 方法

            暂停指定的毫秒数后执行指定的代码

            参数1--指定运行的代码

            参数2--指定的毫秒数

var mytestsetTimeout=null;
function testsetTimeout(){
    var hobj=document.getElementById("test1");
    function mygetDate(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var mydate=date.getDate();
        var hours=date.getHours()
        var minutes=date.getMinutes();
        var seconds=date.getSeconds();
        var time=year+"年"+month+"月"+mydate+"日"+hours+":"+minutes+":"+seconds;
        hobj.innerHTML=time;
    }
    mytestsetTimeout=setTimeout(function(){mygetDate();},3000);
}

         clearTimeout(timeoutVariable) 方法用于停止执行setTimeout()方法的函数代码。

         参数timeoutVariable----setTimeout方法的返回值。

var mytestsetTimeout=null;
function testsetTimeout(){
    var hobj=document.getElementById("test1");
    function mygetDate(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var mydate=date.getDate();
        var hours=date.getHours()
        var minutes=date.getMinutes();
        var seconds=date.getSeconds();
        var time=year+"年"+month+"月"+mydate+"日 "+hours+":"+minutes+":"+seconds;
        hobj.innerHTML=time;
    }
    mytestsetTimeout=setTimeout(function(){mygetDate();},3000);
}
//停止setInterval
function  testclearTimeout(){
    clearTimeout(mytestsetTimeout);
}

 

Guess you like

Origin blog.csdn.net/m0_49935332/article/details/114701405