当前位置:网站首页>BOM notes

BOM notes

2022-06-24 07:46:00 Dregs washing

BOM

One 、BOM summary

1.BOM ( Browser Object Model ) Browser object model , It provides objects that interact with browser windows independently of content , Its core object is window.
2.BOM It consists of a series of related objects , And each object provides many methods and properties .
3.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 .

  • Browser object model

  • hold browser As a object To look at

  • BOM The top-level object of is window

  • BOM What we learn is Browser window interaction Some of the objects of


Two 、BOM The top object of window

  • window Object is an interface to access the browser window

  • window Object is a global object . Variables defined in the global scope 、 Functions will become window Properties and methods of objects .

  • When calling, you can Omit window, Dialog boxes belong to window Object method , Such as alert()、prompt() etc. .


3、 ... and 、window Common events for objects

1. Window load event

grammar

1.window.onload = function() {};

or :window.addEventListener(“load”,function() {});

2.document.addEventListener(‘DOMContentLoaded’,function() {});

explain

1.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 .

2.DOMContentLoaded Event triggered , Only when the DOM Loading complete , Don't include style sheets , picture ,flash wait .IE9 Above support

Be careful

1. With window You can put the JS The code is written above the page element , because onload Yes, wait until all the page contents are loaded , Then execute the processing function .

2.window.onload The traditional method of registering events can only be written once , If more than one , I'll take the last window.onload Subject to . If you use addEventListener There is no limit .

Code example Be careful script Location

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <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>
</head>

<body>

    <button> Click on </button>

</body>

</html>

2. Window resizing Events

grammar :.window.onresize = function() {} ;

​ or :window.addEventLinstner(“resize”,function() {});

explain

window.onresize Is the load event when the window is resized , Handler called when triggered

Be careful

1. As long as the window size changes in pixels , Will trigger this event .

2. We often use this event to do responsive layout .window.innerWidth The width of the current screen

Code example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style> div {
       width: 200px; height: 200px; background-color: pink; } </style>
</head>

<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>

</html>

3. Two timers

(1) setTimeout() Timer

grammar :window.setTimeout( Call function ,[ The number of milliseconds delayed ]);

explain

setTimeout() Method to set a timer , The timer executes the call function after the timer expires

Be careful

1.window You can Omit

2. Delay time Company when millisecond , It can be omitted , If you omit Default Yes. 0

3. This calling function can directly write the function It's fine too Write the function name , You can also write ' Function name ()' however Not recommended

4. There may be many timers in the page , We often add... To timers identifier ( name )

Code example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script> // 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>

</html>

Add

setTimeout() This calling function is also called Callback function callback

Ordinary functions are called directly in code order , But a function needs Waiting time , Only when the time is up will we execute , Therefore calls Callback function .

(2)setInterval() Timer

grammar :window.setInterval( Callback function ,[ The number of milliseconds between ]);

explain

setInterval() Method Repeated calls to A function , At this interval , Just call the callback function once .

Be careful

1.window You can Omit

2. Delay time Company when millisecond , It can be omitted , If you omit Default Yes. 0

3. This calling function can directly write the function It's fine too Write the function name , You can also write ' Function name ()' however Not recommended

4. There may be many timers in the page , We often add... To timers identifier ( name )

Code example

<script>
    serInterval(function() {
    
    console.log(' Continue to output ');
},1000);
</script>

(3) Stop timer

grammar

1.window.clearTimeout(timeoutID);

2.window.claerInterval(intervalID);

explain

Both methods can cancel the timer previously established through the call

Be careful

1.window It can be omitted .

2. The parameters inside are the parameters of the timer identifier .

Code example

setTimeout():

<script>
        var btn = document.querySelector('button');
        var timer = setTimeout(function() {
    
            console.log(' exploded ');

        }, 5000);
        btn.addEventListener('click', function() {
    
            clearTimeout(timer);
        });
</script>

setInterval():

<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>

Add

In the timer this Point to window.


Four 、window Important components of objects

1.location object

window Object provides us with a location Property is used to get or set the name of the form URL , And can be used for parsing URL. Because this property returns an object , So we call this property location object .

(1) URL

Uniform resource locator (Uniform Resource Locator, URL) Is the address of standard resources on the Internet . Every file on the Internet has a unique URL , It contains information indicating the bits of the file and what the browser should do with it .

Grammar format

protocol://host[:port]/path/[?query]#fragment

eg: http://www.itcast.cn/index.html?name=andy&age=18#link

  • protocol: Communication protocol Commonly used http,ftp,maito etc.
  • host: host ( domain name ) www.itcast.com
  • port: Port number Optional , When omitted, the default port of the scheme is 80
  • path: route By zero or more ’/' String separated by symbols , It is generally used to indicate a directory or file address of the host
  • query: Parameters The form of a key value pair , adopt & Separated by symbols
  • fragment: fragment # Later on Common in link anchors

(2) location Object properties

1.location.href: Get or set Whole URL ( a key )

2.location.host: Return to the owner ( domain name ) www.itcast.com

3.location.port: Return port number If not, return An empty string

4.location.pathname: Return path

5.location.search: Returns the parameter ( a key )

6.location.hash: Return fragment # Later Common in links Anchor point

<body>
    <button> Click on </button>
    <script> var btn =document.querySelector('button'); btn.addEventListener('click', function() {
       //console.log(location.href); location.href = 'www.itcast.con'; }) </script>
</body>

(3) location Object method

1.location.assign(): Jump to the page ( Also known as redirection pages )

2.location.replace(): Replace the current page , Because there's no history , So you can't go back to the page

3.location.reload(): Reload page , It's like a refresh button or f5 If the parameter is true Forced refresh ctrl+f5

<body>
    <button> Click on </button>
    <script> var btn = document.querySelector('button'); btn.addEventListener('click', function() {
       // Record browser history , So the backward function is realized  //location.assign('http://www.itcast.con'); // Do not record browsing history , Therefore, the backward function cannot be realized  //location.replace('http://www.itcast.con'); location.reload(true); }) </script>
</body>

2.navigator object

navigator Object contains information about the browser , It has many properties , What we use most 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 of the user opens the page , Realize jump

if((navigator.userAgent.match(/(phone|Ipad|pod|iPhone|iPod|ios|ipad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUCI|Fennec|wOSBrowser|BrowserNG|Webos|Symbian|windows Phone)/i))) {
	window.location.href = ""; // mobile phone 
} else {
	window.location.href =""; //  The computer 

3.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

1.back(): You can go back

2.forward(): Forward function

3.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=""> Click "I go to the home page" </a>
    <button> back off </button>
    <script> var btn = document.querySelector('button'); btn.addEventListener('click', function() {
       //history.back(); history.go(-1); }) </script>
</body>
原网站

版权声明
本文为[Dregs washing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240302427429.html