当前位置:网站首页>JS --- BOM details of JS (V)
JS --- BOM details of JS (V)
2022-07-06 15:22:00 【Cirrod】
1、BOM summary
BOM = Browser Object Model Browser object model
It provides objects that interact with browser windows independently of content , Its core object is window
BOM It consists of a series of related objects , And each object provides many methods and properties
BOM Lack of standards ,JavaScript The standard organization of grammar is ECMA, DOM Our standardization organization is W3C, BOM Initially Netscape Part of the browser standard
DOM | BOM |
Document object model | Browser object model |
DOM Is to put file Treat as an object | hold The browser is treated as an object |
DOM The top-level object of is document | BOM The top-level object of is window |
DOM The main learning is to operate the page elements | BOM Learn some objects that interact with the browser window |
DOM yes W3C Standard specification | BOM It is defined by browser manufacturers on their respective browsers , Poor compatibility |
1.1、BOM The composition of the
BOM Than DOM Bigger . It contains DOM.
window Object is the top-level object of the browser , It has a dual role
It is JS An interface for accessing browser windows
It's a global object . Variables defined in the global scope 、 Functions will become window Properties and methods of objects
You can omit... When calling window, The previous dialog boxes belong to window Object methods , Such as alert()、prompt() etc. .
Be careful :window One of the special properties of the following window.name
// Variables defined in the global scope become window Object properties
var num = 10;
console.log(window.num);
// 10
// The function defined in the global scope will become window Object method
function fn() {
console.log(11);
}
console.fn();
// 11
var name = 10; // Don't use this name Variable ,window There is a special attribute under window.name
console.log(window.num);
2、window Common events for objects
2.1、 Window load event
window.onload It's the window ( page ) Loading event , This event is triggered when the document content is fully loaded ( Include images , Script files ,CSS Documents, etc. ), Just call the handler .
window.onload = function(){
};
// perhaps
window.addEventListener("load",function(){});
Be careful :
With window.onload You can put the JS The code is written to the top of the page element
because onload Yes, wait until all the page contents are loaded , Then execute the processing function
window.onload The traditional way of registering events , Write only once
If there are more than one , I'll take the last window.onload Subject to
If you use addEventListener There is no limit
document.addEventListener('DOMContentLoaded',function(){})
Receive two parameters :
DOMCountentLoaded Event triggered , Only when the DOM Loading complete , Don't include style sheets , picture ,flash wait
If there are many pictures on the page , From user access to onload Triggering can take a long time
Interaction can't be realized , It's bound to affect the user experience , Use at this time DOMContentLoaded Events are more appropriate .
2.1.1、 difference
load Wait until all the page contents are loaded , Include page dom Elements , picture ,flash,css etc.
DOMContentLoaded yes DOM Loading finished , No pictures flash css You can execute it later , Loading speed ratio load Faster
<script>
// window.onload = function() {
// var btn = document.querySelector('button');
// btn.addEventListener('click', function() {
// alert(' Click on the I ');
// })
// }
// window.onload = function() {
// alert(22);
// }
window.addEventListener('load', function() {
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
alert(' Click on the I ');
})
})
window.addEventListener('load', function() {
alert(22);
})
document.addEventListener('DOMContentLoaded', function() {
alert(33);
})
// load Wait until all the page contents are loaded , Include page dom Elements picture flash css wait
// DOMContentLoaded yes DOM Loading finished , No pictures falsh css You can execute it later Loading speed ratio load Faster
</script>
2.2、 Window resizing Events
window.onresize Is to adjust the window size to load events , Handler function called when triggered
window.onresize = function() {}
// perhaps
window.addEventListener('resize',function(){});
As long as the window size changes in pixels , Will trigger this event
We often use this event to do responsive layout .window.innerWidth The width of the current screen
<body>
<script>
window.addEventListener('load', function() {
var div = document.querySelector('div');
window.addEventListener('resize', function() {
console.log(window.innerWidth);
console.log(' Changed ');
if (window.innerWidth <= 800) {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
})
})
</script>
<div></div>
</body>
3、 Timer
window Object provides us with two timers
setTimeout()
setInterval()
3.1、setTimeout() Timer
setTimeout() Method to set a timer , The timer executes the call function after the timer expires .
window.setTimeout( Call function ,[ The number of milliseconds delayed ]);
Be careful :
window It can be omitted
This calling function
You can write functions directly
Or write the function name
Or take a string ‘ Function name ()’ ( Not recommended )
The number of milliseconds to delay is omitted. The default is 0, If write , It has to be milliseconds
Because timers can have a lot of , So we often assign an identifier to the timer
setTimeout() This calling function is also called a callback function callback
Ordinary functions are called directly in code order , And this function , Need to wait for events , This function will not be called until the event arrives , So it's called a callback function .
<body>
<script>
// 1. setTimeout
// Grammatical norms : window.setTimeout( Call function , Delay Time );
// 1. This window You can omit... When calling
// 2. The delay time is in milliseconds But you can omit , If omitted, the default is 0
// 3. This calling function can directly write the function You can also write Function name There's another way to write it ' Function name ()'
// 4. There may be many timers in the page , We often add identifiers to timers ( name )
// setTimeout(function() {
// console.log(' time out ');
// }, 2000);
function callback() {
console.log(' exploded ');
}
var timer1 = setTimeout(callback, 3000);
var timer2 = setTimeout(callback, 5000);
// setTimeout('callback()', 3000); // We don't advocate this way of writing
</script>
</body>
3.2、clearTimeout() Stop timer
clearTimeout() Method cancels the previous call setTimeout() Set up a timer
window.clearTimeout(timeoutID)
Be careful :
window It can be omitted
The parameter inside is the identifier of the timer
<body>
<button> Click stop timer </button>
<script>
var btn = document.querySelector('button');
var timer = setTimeout(function() {
console.log(' exploded ');
}, 5000);
btn.addEventListener('click', function() {
clearTimeout(timer);
})
</script>
</body>
3.3、setInterval() Timer
setInterval() Method repeatedly calls a function , Every once in a while , Just call the callback function once
window.setInterval( Callback function ,[ The number of milliseconds between ]);
window It can be omitted
This callback function :
You can write functions directly
Or write the function name
Or take characters ‘ Function name ()’
The first execution is also executed after an interval of milliseconds , After that, it is executed every millisecond
<body>
<script>
// 1. setInterval
// Grammatical norms : window.setInterval( Call function , Delay Time );
setInterval(function() {
console.log(' Continue to output ');
}, 1000);
// 2. setTimeout The delay time is up , Just call this callback function , Call it once It ends the timer
// 3. setInterval Every time this delay time , Just call this callback function , Will be called many times , Call this function repeatedly
</script>
</body>
3.4、clearInterval() Stop timer
clearInterval ( ) Method cancels the previous call setInterval() Set up a timer
Be careful :
window It can be omitted
The parameter inside is the identifier of the timer
<body>
<button class="begin"> Turn on timer </button>
<button class="stop"> Stop timer </button>
<script>
var begin = document.querySelector('.begin');
var stop = document.querySelector('.stop');
var timer = null; // Global variables null Is an empty object
begin.addEventListener('click', function() {
timer = setInterval(function() {
console.log('ni hao ma');
}, 1000);
})
stop.addEventListener('click', function() {
clearInterval(timer);
})
</script>
</body>
3.5、this Point to
this The direction of is not certain when the function is defined , It can only be determined when the function is executing this Who is it pointing to
At this stage , Let's start with a few this Point to
Global scope or ordinary function this Point to global object window( Pay attention to the... In the timer this Point to window)
Who calls... In method calls this Point to the who
In the constructor this Point to constructor instance
<body>
<button> Click on </button>
<script>
// this Point to the problem In general this Finally, it points to the object that calls it
// 1. Global scope or ordinary function this Point to global object window( Pay attention to the... In the timer this Point to window)
console.log(this);
function fn() {
console.log(this);
}
window.fn();
window.setTimeout(function() {
console.log(this);
}, 1000);
// 2. Who calls... In method calls this Point to the who
var o = {
sayHi: function() {
console.log(this); // this Pointing to o This object
}
}
o.sayHi();
var btn = document.querySelector('button');
// btn.onclick = function() {
// console.log(this); // this Pointing to btn This button object
// }
btn.addEventListener('click', function() {
console.log(this); // this Pointing to btn This button object
})
// 3. In the constructor this Point to an instance of the constructor
function Fun() {
console.log(this); // this Pointing to fun Instance object
}
var fun = new Fun();
</script>
</body>
4、JS Execution mechanism
4.1、JS A single thread
JavaScript One of the characteristics of language is single thread , in other words , Only one thing can be done at a time . This is because Javascript The mission of the birth of this scripting language ——JavaScript Is to handle user interaction in a page , And operation DOM The birth of the . For example, we have a DOM Element to add and delete , It can't be done at the same time . You should add... First , Delete later .
Single thread means , All tasks are queued , The previous task is over , Will perform the latter task . The problem with this is : If JS The execution took too long , This causes the page to render inconsistently , The feeling of blocking page rendering load .
4.2、 A problem
What is the result of the execution of the following code ?
console.log(1);
setTimeout(function() {
console.log(3);
},1000);
console.log(2);
So what is the result of the following code execution ?
console.log(1);
setTimeout(function() {
console.log(3);
},0);
console.log(2);
4.3、 Synchronous and asynchronous
To solve this problem , Using multiple cores CPU Computing power ,HTML5 Put forward Web Worker standard , allow JavaScript The script creates multiple threads
therefore ,JS There are synchronous and asynchronous .
Sync :
Perform the next task after the previous one
asynchronous :
While doing this , You can deal with other things
Synchronization task
Synchronization tasks are performed on the main thread , To form a Execution stack
Asynchronous task
JS Asynchrony in is realized through callback function
There are three types of asynchronous tasks
Ordinary events , Such as click,resize etc.
Resource loading , Such as load,error etc.
Timer , Include setInterval,setTimeout etc.
Asynchronous task related callback functions are added to the task queue
Perform the synchronization task in the execution stack first
Asynchronous task ( Callback function ) Put it in the task queue
Once all synchronization tasks in the execution stack are completed , The system will read the asynchronous tasks in the task queue in order , The read asynchronous task ends waiting , Enter the execution stack , Start execution
Now let's look at our question just now :
console.log(1);
setTimeout(function() {
console.log(3);
},1000);
console.log(2);
The results and order of execution are 1、2、3
console.log(1);
setTimeout(function() {
console.log(3);
},0);
console.log(2);
The results and order of execution are 1、2、3
// 3. Third question
console.log(1);
document.onclick = function() {
console.log('click');
}
console.log(2);
setTimeout(function() {
console.log(3)
}, 3000)
The synchronization task is executed in the execution stack , Asynchronous tasks are processed by asynchronous processes and placed in the task queue , After the tasks in the execution stack are executed, you will go to the task queue to check whether there are asynchronous tasks executing , Because the main thread repeatedly gets tasks 、 Perform tasks 、 Get the mission again 、 Re execution , So this mechanism is called event loop ( event loop).
5、location object
window Object provides us with a location Property is used to get or set the name of the form url, And we can parse url. Because this property returns an object , So we call this property location object .
5.1、url
== Uniform resource locator (uniform resouce locator)== Is the address of standard resources on the Internet . Every file on the Internet has a unique URL, It contains information about the location of the file and how the browser should handle it .
url The general syntax of is :
protocol://host[:port]/path/[?query]#fragment
http://www.itcast.cn/index.html?name=andy&age=18#link
form | explain |
protocol | Communication protocol frequently-used http,ftp,maito etc. |
host | host ( domain name ) www.itheima.com |
port | Port number , Optional |
path | route By zero or more '/' String separated by symbols |
query | Parameters In the form of key value pairs , adopt & Separated by symbols |
fragment | fragment # Later on Common in links Anchor point |
5.2、location Object properties
location Object properties | Return value |
location.href | Gets or sets the entire URL |
location.host | Back to the host ( domain name )www.baidu.com |
location.port | Return port number , Returns an empty string if not written |
location.pathname | Return path |
location.search | Returns the parameter |
location.hash | Return fragment # The following content is common in links Anchor point |
The point is to remember : href and search
demand :5s Then jump to the page
<body>
<button> Click on </button>
<div></div>
<script>
var btn = document.querySelector('button');
var div = document.querySelector('div');
var timer = 5;
setInterval(function() {
if (timer == 0) {
location.href = 'http://www.itcast.cn';
} else {
div.innerHTML = ' You will be at ' + timer + ' Seconds later, jump to the home page ';
timer--;
}
}, 1000);
</script>
</body>
5.3、location Object methods
location Object methods | Return value |
location.assign() | Follow href equally , You can jump to the page ( Also known as redirection pages ) |
location.replace() | Replace the current page , Because there's no history , So you can't go back to the page |
location.reload() | Reload page , It's like a refresh button or f5 , If the parameter is true Forced to refresh ctrl+f5 |
<body>
<button> Click on </button>
<script>
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
// Record browsing history , So it can realize the backward function
// location.assign('http://www.itcast.cn');
// Do not record browsing history , Therefore, the backward function cannot be realized
// location.replace('http://www.itcast.cn');
location.reload(true);
})
</script>
</body>
5.4、 obtain URL Parameters
Let's simply write a login box , Click login to jump to index.html
<body>
<form action="index.html">
user name : <input type="text" name="uname">
<input type="submit" value=" Sign in ">
</form>
</body>
So let's say that index.html
<body>
<div></div>
<script>
console.log(location.search); // ?uname=andy
// 1. Remove first ? substr(' Starting position ', Intercept a few characters );
var params = location.search.substr(1); // uname=andy
console.log(params);
// 2. utilize = Splits a string into arrays split('=');
var arr = params.split('=');
console.log(arr); // ["uname", "ANDY"]
var div = document.querySelector('div');
// 3. Write data to div in
div.innerHTML = arr[1] + ' Welcome ';
</script>
</body>
So we can get the... On the path URL Parameters
6、navigator object
navigator Object contains information about the browser , It has many properties
What we often use is userAgent, This property returns the message sent by the client to the server user-agent The value of the head
The following front-end code can determine which terminal the user uses to open the page , If it is to use PC The open , We'll jump to PC End page , If it was opened with a mobile phone , Jump to the mobile page
if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
window.location.href = ""; // mobile phone
} else {
window.location.href = ""; // The computer
}
7、history object
window Object provides us with a history object , Interact with browser history
This object contains the user ( In the browser window ) Visited URL.
history Object methods | effect |
back() | You can go back |
forward() | Forward function |
go( Parameters ) | Forward and backward function , If the parameter is 1 Forward 1 A page If it is -1 back off 1 A page |
<body>
<a href="list.html"> Click me to go to the list page </a>
<button> Forward </button>
<script>
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
// history.forward();
history.go(1);
})
</script>
</body>
边栏推荐
- Global and Chinese market for antiviral coatings 2022-2028: Research Report on technology, participants, trends, market size and share
- Maximum nesting depth of parentheses in leetcode simple questions
- ucore lab2 物理内存管理 实验报告
- How to do agile testing in automated testing?
- Rearrange spaces between words in leetcode simple questions
- Description of Vos storage space, bandwidth occupation and PPS requirements
- The minimum number of operations to convert strings in leetcode simple problem
- Global and Chinese market of DVD recorders 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese markets of electronic grade hexafluorobutadiene (C4F6) 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese markets for complex programmable logic devices 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
全网最详细的postman接口测试教程,一篇文章满足你
自动化测试你必须要弄懂的问题,精品总结
Brief description of compiler optimization level
線程及線程池
Knowledge that you need to know when changing to software testing
自动化测试中敏捷测试怎么做?
基于485总线的评分系统双机实验报告
Lab 8 文件系统
China's county life record: go upstairs to the Internet, go downstairs' code the Great Wall '
MySQL数据库(一)
随机推荐
What are the commonly used SQL statements in software testing?
pytest
CSAPP家庭作业答案7 8 9章
Capitalize the title of leetcode simple question
How to do agile testing in automated testing?
What is "test paper test" in software testing requirements analysis
MySQL transactions
ucore lab1 系统软件启动过程 实验报告
Mysql database (IV) transactions and functions
Lab 8 文件系统
Leetcode simple question: check whether the numbers in the sentence are increasing
Collection集合与Map集合
自动化测试中敏捷测试怎么做?
想跳槽?面试软件测试需要掌握的7个技能你知道吗
Dlib detects blink times based on video stream
Global and Chinese market of goat milk powder 2022-2028: Research Report on technology, participants, trends, market size and share
ucore Lab 1 系统软件启动过程
Réponses aux devoirs du csapp 7 8 9
Crawler series (9): item+pipeline data storage
LeetCode#118. Yanghui triangle