current position:Home>Javascript based BOM

Javascript based BOM

2022-04-29 08:09:00Chen Chen is trying

BOM

Browser object model (browser object model)

BOM We can get us through JS To operate the browser

stay BOM Provides us with a set of objects , Used to complete the operation of the browser

BOM object :

  • Window Represents the entire browser window , meanwhile window It's also a global object in a web page
  • Navigator Represents the current browser information , This object allows you to identify different browsers
  • Location Represents the address bar information of the current browser , adopt Location You can get the address bar information , Or operate the browser to jump to the page
  • History Represents the history of the browser , You can use this object to manipulate the browser's history . For privacy reasons , The object cannot get the specific history , Can only operate the browser forward or backward page . And this operation is only valid when accessed .
  • Screen Information representing the user's screen , Through this object, the relevant information of the user's display can be obtained

these BOM Objects are used in browsers as window The properties of the object are saved , Can pass window Object to use , It can also be used directly

Navigator

Represents the current browser information , This object allows you to identify different browsers

For historical reasons ,Navigator Most of the properties in the object can no longer help us identify the browser

userAgent

Generally, we only use userAgent To determine the browser's information ,userAgent Is a string , This string contains useful content to describe the browser information

Different browsers have different userAgent

  • Fox's userAgent
    • Mozilla5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko20100101 Firefox50.0
  • Chrome Of userAgent
    • Mozilla5.0 (Windows NT 6.1; Win64; x64) AppleWebKit537.36 (KHTML, like Gecko) Chrome52.0.2743.82 Safari537.36
  • IE8
    • Mozilla4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  • IE9
    • Mozilla5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  • IE10
    • Mozilla5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  • IE11
    • Mozilla5.0 (Windows NT 6.1; WOW64; Trident7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko

stay IE11 Microsoft and IE The relevant signs have been removed , So we basically can't pass UserAgent To identify whether a browser is IE 了

alert(navigator.appName);  
  
var ua = navigator.userAgent;  
  
console.log(ua);  
  
if(firefoxi.test(ua)){
      
alert(" You're Firefox !!!");  
}else if(chromei.test(ua)){
      
alert(" You are a Chrome");  
}else if(msiei.test(ua)){
      
alert(" You are a IE browser ~~~");  
}else if("ActiveXObject" in window){
      
alert(" You are a IE11, Shoot you ~~~");  
}  

History

Object can be used to manipulate the browser to page forward or backward

  • length You can get the number of links visited by the browser at that time
  • back() Can be used to go back to the previous page , It works the same as the browser's back button
  • forward() You can jump to the next page , It works the same way as the browser's forward button
  • go() It can be used to jump to the specified page . It takes an integer as a parameter :
    • 1: Means to jump forward to a page amount to forward()
    • 2: It means to jump forward two pages
    • -1: Means to jump back to a page
    • -2: Means to jump back two pages

Location

This object encapsulates the information of the browser's address bar

If you print directly location, You can get the information in the address bar ( The full path of the current page ):alert(location);

If you will location Property to a complete path , Or relative path . Then our page will automatically jump to this path , And the corresponding history will be generated

location = "http:www.baidu.com";

location = "01.BOM.html";

location Object methods

  • assign() Used to jump to other pages , Function and direct modification location equally
  • reload() Used to reload the current page , It works the same as the refresh button If you pass a in a method true, As a parameter , The cache will be forced to clear and refresh the page
  • replace() You can replace the current page with a new page , After calling, it will also jump to the page . No history will be generated , You can't use the back button to go back

window

Timer

setInterval() Timed call

You can put a function , Execute at regular intervals . Parameters :

  1. Callback function , This function is called at regular intervals
  2. Time between calls , In milliseconds

Return value : Return to one Number Data of type , This number is used as the unique identification of the timer

clearInterval() Can be used to turn off a timer

Method requires the identification of a timer as a parameter , This will turn off the timer corresponding to the identification

clearInterval() Can receive any parameter , If the parameter is the identification of a valid timer , Then stop the corresponding timer

If the parameter is not a valid identifier , And do nothing

var num = 1;  
var timer = setInterval(function() {
      
	count.innerHTML = num++;  
	if(num == 11) {
      
		// off timer  
		clearInterval(timer);  
	}  
}, 1000);  

Delay call

setTimeout

Delay calling a function without immediate execution , But after a period of time , And it's only going to be executed once

Difference between delayed call and timed call : A timed call will execute multiple times , The deferred call is executed only once

Deferred calls and timed calls can actually replace each other , In development, you can choose according to your own needs

var timer = setTimeout(function(){
      
	console.log(num++);  
},3000);  

clearTimeout()

To close a deferred call :clearTimeout(timer);

Class operation

Directly modify the class of the element css:

adopt style Attribute to modify the style of an element , Every time you change a style , The browser needs to render the page again . The performance of such execution is relatively poor , And this form when we want to modify multiple styles , It's not very convenient I want one line of code , You can modify multiple styles at the same time

We can modify the class Property to modify the style indirectly . thus , We only need to modify it once , You can modify multiple styles at the same time , The browser only needs to re render the page once , Good performance , And this way , It can further separate performance from behavior

box.className += " b2";	// Notice that there are spaces , add to class attribute  
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.b1 {
    
				width: 100px;
				height: 100px;
				background-color: red;
			}

			.b2 {
    
				height: 300px;
				background-color: yellow;
			}
		</style>

		<script type="text/javascript">
			window.onload = function() {
    
				// obtain box
				var box = document.getElementById("box");
				// obtain btn01
				var btn01 = document.getElementById("btn01");

				// by btn01 Binding click response function 
				btn01.onclick = function() {
    
					// modify box The style of 
					/* *  adopt style Attribute to modify the style of an element , Every time you change a style , The browser needs to render the page again  *  The performance of such execution is relatively poor , And this form when we want to modify multiple styles , It's not very convenient  */
					/*box.style.width = "200px"; box.style.height = "200px"; box.style.backgroundColor = "yellow";*/

					/* *  I want one line of code , You can modify multiple styles at the same time  */

					// modify box Of class attribute 
					/* *  We can modify the class Property to modify the style indirectly  *  thus , We only need to modify it once , You can modify multiple styles at the same time , *  The browser only needs to re render the page once , Good performance , *  And this way , It can further separate performance from behavior  */
					//box.className += " b2";
					//addClass(box,"b2");

					//alert(hasClass(box,"hello"));

					//removeClass(box,"b2");

					toggleClass(box, "b2");
				};

			};

			// Define a function , Used to add a specified class Property value 
			/* *  Parameters : * obj  You want to add class Attribute elements  * cn  To add class value  * */
			function addClass(obj, cn) {
    

				// Check obj Whether contains cn
				if(!hasClass(obj, cn)) {
    
					obj.className += " " + cn;
				}

			}

			/* *  Determine whether an element contains the specified class Property value  *  If there is class, Then return to true, No return false * */
			function hasClass(obj, cn) {
    

				// Judge obj Is there a cn class
				// Create a regular expression 
				//var reg = /\bb2\b/;
				var reg = new RegExp("\\b" + cn + "\\b");

				return reg.test(obj.className);

			}

			/* *  Delete the specified... From an element class attribute  */
			function removeClass(obj, cn) {
    
				// Create a regular expression 
				var reg = new RegExp("\\b" + cn + "\\b");

				// Delete class
				obj.className = obj.className.replace(reg, "");

			}

			/* * toggleClass Can be used to switch a class  *  If the element has this class , Delete  *  If there is no such class in the element , Then add  */
			function toggleClass(obj, cn) {
    

				// Judge obj Whether contains cn
				if(hasClass(obj, cn)) {
    
					// Yes , Delete 
					removeClass(obj, cn);
				} else {
    
					// No, , Then add 
					addClass(obj, cn);
				}
			}
		</script>
	</head>

	<body>
		<button id="btn01"> Click the button to modify later box The style of </button>
		<br /><br />
		<div id="box" class="b1 b2"></div>
	</body>

</html>

JSON

JavaScript Object Notation JS Object notation

JSON Format

  1. The value of a compound type can only be an array or an object , It can't be a function 、 Regular expression objects 、 Date object .
  2. There are only four values of the original type : character string 、 The number ( Must be expressed in decimal )、 Boolean and null( Out of commission NaN, Infinity, -Infinity and undefined).
  3. character string You must use double quotation marks to indicate , You can't use single quotes .
  4. The key name of the object must be placed in double quotes .
  5. After the last member of an array or object , No commas .

JS Objects in are JS I know myself , I don't know any other languages

JSON Is a special format string , This string can be recognized by any language , And can be converted to any language object ,JSON It is mainly used for data interaction in development

JSON and JS The format of the object is the same , It's just JSON Property names in strings must be double quoted . Others and JS Grammar is the same

JSON classification :

  1. object {}
  2. Array []

JSON Values allowed in :

  1. character string
  2. The number
  3. Boolean value
  4. null
  5. object
  6. Array

give an example :

var arr = '[1,2,3,"hello",true]';  
			  
var obj2 = '{"arr":[1,2,3]}';  
  
var arr2 ='[{"name":" The Monkey King ","age":18,"gender":" male "},{"name":" The Monkey King ","age":18,"gender":" male "}]';  

JSON Tool class

stay JS A tool class is provided for us in , Call JSON, This object can help us implement JSON and JS Cross conversion

JSON This object is IE7 Not supported in browsers and below , So when you call in these browsers, you will report errors.

json ——> js object

JSON.parse() We can use JSON String conversion to js object .

It needs a JSON String as argument , The string is converted to JS Object and return

var json = '{"name":" The Monkey King ","age":18,"gender":" male "}';
var arr = '[1,2,3,"hello",true]';
var o = JSON.parse(json);  
var o2 = JSON.parse(arr);  

JS object ——> JSON

JSON.stringify() You can put a JS Object to JSON character string

Need one js Object as parameter , Will return a JSON character string

var obj3 = {
    name:" Pig eight quit " , age:28 , gender:" male "};
var str = JSON.stringify(obj3);

other

localStorage

read-only localStorage Property allows you to access a Document Source (origin) The object of Storage; Its stored data can be retained in cross browser sessions .localStorage similar sessionStorage, But the difference is : Stored in localStorage The data can be kept for a long time ; And when the page session ends —— in other words , When the page is closed , Stored in sessionStorage The data will be cleared .

eval()

eval() This function can be used to execute a string JS Code , And return the execution result to .

If you use eval() The executed string contains {}, It will be {} Think of it as a code block ; If you don't want to parse it as a code block , You need to add one before and one after the string ()

eval() This function is very powerful , You can directly execute the js Code , But try not to use it in development , First of all, its performance is poor , Then it has security risks .

If you need compatibility IE7 And the following JSON operation , By introducing an external js File to process .

var str = '{"name":" The Monkey King ","age":18,"gender":" male "}';  
var obj = eval("("+str+")");  
console.log(obj);

Native js

Native js Copy content to the clipboard

copy() {
      
    const input = document.createElement("input");  
    document.body.appendChild(input);  
    input.setAttribute("value",this.solution.code);  
    input.select();  
    if (document.execCommand("copy")) {
      
        document.execCommand("copy");  
        // console.log(" Replication success "); 
    }  
    document.body.removeChild(input);  
}  

·

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290808569161.html

Random recommended