Search “Program Yuan Xiaozhuang” on wechat, and you will get a full set of Python full stack tutorials, as well as the constantly updated e-books and interview materials prepared by Xiaozhuang
preface
So far, I have learned the simple syntax of JavaScript, but it does not interact with the browser. The syntax I have learned so far does not control the behavior of the web page. If you want to control the behavior of the web page, you need to continue to learn BOM and DOM
BOM
BOM (Browser Object Model) refers to the Browser Object Model, which enables JavaScript to “talk” to the Browser.
The window object
All browsers support the Window object, which represents the browser window. All JavaScript global objects automatically become properties or methods of the Window object, including the Document introduced in DOM manipulation.
Here are some common window methods:
// Height of the browser window
window.innerHeight
// Width of the browser window
window.innerWidth
// Create a new window to open the page
window.open('https://juejin.cn/user/298666235012894'.' '.'height=400px,width=400px,top=400px,left=400px')
/* The first parameter is the url of the page opened by the new window. The second parameter is blank. The third parameter is the position and size of the new window
// Close the current page
window.close()
Copy the code
Child object of window
The Window object is one of the highest level objects in client-side JavaScript. Since the Window object is the common ancestor of most other objects, references to the Window object can be omitted when calling its methods and properties.
The navigator object
Browser object, which determines that the browser the user is using also contains information about the browser.
// The name of the browser (window object can be omitted)
navigator.appName
// "Netscape"
// Browser version
window.navigator.appVersion
// "5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
// Indicates whether it is currently a browser
navigator.userAgent;
// "Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
// Check which platform the current browser is running on
navigator.platform;
// "Win32"
Copy the code
The history object
The browser history object, which contains the user’s browsing history of the current page, but can be used simply to move a page forward or backward.
// Go back to the previous page
history.back();
// Proceed to the next page
window.history.forward();
Copy the code
Location object
Get the URL of the current page and redirect the browser to the new page.
// Get the url of the current page
location.href;
// Jump to the specified URL
window.location.href = 'Target url';
// Refresh the page, which is equivalent to the refresh function on the browser
window.location.reload();
Copy the code
pop-up
You can create three message prompt boxes in JavaScript: warning, confirmation, and prompt.
// Warning box: window.alter(' popup content ')
window.alert('warning! ');
// Window.confirm (' what to confirm ')
window.confirm('yes or no'); // Ok returns true, Cancel returns false
// Prompt box: window.prompt(' prompt message ', 'default value ')
window.prompt('Save password or not'.'yes'); // Return what the user typed
Copy the code
timing
In JavaScript, you can execute code after a certain interval, rather than calling a function and executing it immediately.
setTimeout()
Trigger once and only once after a certain period of time.
// Syntax: setTimeout(js code, milliseconds), indicates the number of milliseconds after the automatic execution of js code
function func() {
alert('ha ha')}setTimeout(func,3000) // The unit is milliseconds, and the func function is automatically executed after 3s
Copy the code
ClearTimeout () – Cancels a scheduled task
function func() {
alert('ha ha')}let t = setTimeout(func,3000) // The unit is milliseconds, and the func function is automatically executed after 3s
clearTimeout(t) // Cancel the scheduled task. Use a variable to refer to the canceled scheduled task
Copy the code
SetInterval () – Triggers the task in a loop
function func() {
alert('ha ha')}function show() {
let t = setInterval(func,3000); // Automatically executes the func function after 3 seconds
function inner() {
clearInterval(t) // Clear the timer
}
setTimeout(inner,9000) Inner function is triggered after 9s
}
Copy the code
DOM
DOM (Document Object Model) refers to the Document Object Model, through which you can access all the elements of an HTML Document. DOM is a set of methods for abstracting and conceptualizing the contents of a document. When a web page is clipped, the browser creates a document object model of the page.
The DOM tree
DOM specifies that each element in an HTML document is a node, as shown below:
Document nodes (Document objects) represent the entire document;
The element node (element object) represents an element (tag);
The text node (text object) represents the text in the element (tag);
Attribute object: represents an attribute. An element (tag) has an attribute.
Comments are comment nodes (comment objects);
The role of DOM manipulation
-
Javascript can create HTML dynamically through the DOM
-
JavaScript can change all HTML elements in a page
-
JavaScript can change all HTML attributes on a page
-
JavaScript can change all CSS styles in a page
-
JavaScript can react to all events on a page
The basic flow of DOM manipulation
DOM operates on tags, and there are many tags in an HTML document. Therefore, DOM operations on tags basically follow the following process:
① Know how to find the label first
② Use DOM to operate labels
③ DOM operations need to start with the keyword document
DOM manipulation – Find tags
Direct search
Direct tag lookup can be performed by tag name, tag ID, and class attributes.
// Find the name of the object is usually: tag name Ele
pEles = document.getElementsByTagName('p'); // Return a collection of tags based on the tag name
pEle = pEles[0] // Get the first tag in the collection
divEle = docunment.getElementByClassName('c1'); // According to the tag attribute, get the tag collection
divEle = document.getElementById('d1'); // Get the tag by the tag id
Copy the code
Indirect search
Indirect lookup can be based on the relative relationship between tags:
// Get the parent node of the p tag
pEle.parentElement;
// Get the first child tag
divEle.firstElementChild
// Get the last child tag
divEle.lastElementChild
// The first tag below the same level
divEle.nextElementSibling
// The previous label of the same level
divEle.previousElementSibling
Copy the code
DOM manipulation – Node manipulation
Tags can be created dynamically through DOM manipulation, and attributes can be added to tags, but these are temporary.
Create a node
// syntax: let/var name = document.createElement(' tag name ');
let aEle = document.createElement('a');
Copy the code
Tag Add attribute
var divEle = document.getElementById("d1");
divEle.setAttribute("age"."18")
divEle.getAttribute("age")
divEle.removeAttribute("age")
// The built-in attributes can also be used directly. Property name to get and set
imgEle.src
imgEle.src="..."
Copy the code
Add a node
InsertBefore (newNode, somenode child node);
let divEle = document.getElementById('d1');
let pEle = document.getElementByClassName('p1');
divEle.insertBefore('aEle'.'pEle') // Insert the a tag before the p tag inside the div
Copy the code
The innerText with innerHTML
// Get all the text in the tag
divEle.innerText;
// Get both the internal text and the label
divEle.innerHTML;
// The difference between the two:
divEle.innerText = 'heiheihei'
"heiheihei"
divEle.innerHTML = 'hahahaha'
"hahahaha"
divEle.innerText = '<h1>heiheihei</h1>' // Do not recognize HTML tags
"<h1>heiheihei</h1>"
divEle.innerHTML = '<h1>hahahaha</h1>' // Identify HTML tags
"<h1>hahahaha</h1>"
Copy the code
DOM manipulation – Get value operation
Gets the data inside the user data tag
let seEle = document.getElementById('d2'); Seel. value;Copy the code
Obtain the file data uploaded by the user
let fileEle = document.getElementById('d3');
// Cannot get file data directly with.value
fileEle.value;
// Use the following method to obtain the file data uploaded by the user
fileEle.files;
fileEle.files[0] # get file dataCopy the code
DOM manipulation – Tag attribute class manipulation
Gets all the class attributes of the tag
let divEle = document.getElementById('d1');
divEle.classList;
// DOMTokenList(3) ["c1", "bg_red", "bg_green", value: "c1 bg_red bg_green"]
Copy the code
Removes a class attribute
divEle.classList.remove('bg_red');
Copy the code
Adding class Attributes
divEle.classList.add('bg_red')
Copy the code
Verify that the tag contains a class attribute
divEle.classList.contains('c1');
// returns true or false
Copy the code
Magic operation, have this attribute to delete, do not add
divEle.classList.toggle('bg_red')
false
divEle.classList.toggle('bg_red')
true
divEle.classList.toggle('bg_red')
false
divEle.classList.toggle('bg_red')
true
Copy the code
DOM manipulation – CSS manipulation
DOM manipulation of the label style, using the same style.
let pEle = document.getElementsByTagName('p') [0]
undefined
pEle.style.color = 'red'
"red"
pEle.style.fontSize = '28px'
"28px"
pEle.style.backgroundColor = 'yellow'
"yellow"
pEle.style.border = '3px solid red'
"3px solid red"
Copy the code
The event
One of the new features of HTML is the ability to cause HTML events to trigger actions in the browser, such as launching a piece of JavaScript when a user clicks on an HTML element.
HTML tags bind events in two ways
<! -- The first kind -->// onclick is a mouse click on a button<button onclick="func1()">Am I</button>;
<script>
function func1() {
alert(111)}</script>
<! -- Second kind -->
<button id="d1">Am I</button>;
<script>
let btnEle = document.getElementById('d1');
btnEle.onclick = function () {
alert(222)}</script>
Copy the code
Native JS event small case
On and off lights – color switch
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d1 {
height: 200px;
width: 200px;
border: 3px solid black;
border-radius: 50%;
}
.green {
background: green;
}
.red {
background: deeppink;
}
</style>
</head>
<body>
<div id='d1' class=" green red">
</div>
<button id="d2">discoloration</button>
<script>
let btnEle = document.getElementById('d2');
let divEle = document.getElementById('d1');
btnEle.onclick = function () { // Bind the click event
// Dynamically modify the class attributes of the div tag
divEle.classList.toggle('red')}</script>
</body>
Copy the code
The input box loses focus
<body>
username:<input type="text" value="Username" id="i1">
<script>
// Get the label object first
let iEle = document.getElementById('i1');
// Bind events to tag objects -- get focus
iEle.onfocus = function () {
iEle.value = ' '
};
// Lose focus
iEle.onblur = function () {
iEle.value = 'Username'
}
</script>
</body>
Copy the code
Displays the current time in real time
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d1 {
display: block;
height: 30px;
width:200px;
}
</style>
</head>
<body>
time:<input type="text" id="d1">
<button id="d2">start</button>
<button id="d3">The end of the</button>
<script>
let t = null
let inputEle = document.getElementById('d1');
let startEle = document.getElementById('d2');
let endEle = document.getElementById('d3');
// Define the display time function
function showTime() {
let currentTime = new Date(a); inputEle.value = currentTime.toLocaleString() }// Bind the start timer to the start button
startEle.onclick = function () {
// If determines that only one timer can be set
if(! t){ t =setInterval(showTime,1000)}};// End the timer for the stop button binding
endEle.onclick = function () {
clearInterval(t);
// After stopping the timer, you cannot start it again without setting t to null because there is only one timer
t = null
}
</script>
</body>
Copy the code
Provinces and cities linkage
<head>
<meta charset="UTF-8">
</head>
<body>Save:<select name="" id="d1">
<option value="" selected disabled>-- Please select --</option>
</select>City:<select name="" id="d2">
<option value="" selected disabled>-- Please select --</option>
</select>
<script>
// Get the label object
let proEle = document.getElementById('d1');
let cityEle = document.getElementById('d2');
// Simulate provincial data
data = {
"Hebei": ["Langfang"."Handan".'the tangshan']."Beijing": ["Chaoyang District".Haidian District.'Changping District']."Shandong": ["Weihai"."Yantai city".'Linyi'].'Shanghai': ['Pudong New Area'.'Jing 'an'.'Huangpu District'].'shenzhen': ['Nanshan'.'Bao 'an District'.'Futian District']};// the for loop gets the province
for (let key in data) {
// Make the provincial information into an option tag and put it in the SELECT tag
let optELe = document.createElement('option');
// Set the text
optELe.innerText = key;
/ / set the value
optELe.value = key;
// Place your option tag in the provincial select tag
proEle.appendChild(optELe)
}
// Analog city data
// Text field change event change event, achieve the effect: select the province appears the corresponding city information
proEle.onchange = function () {
// Get the province selected by the user
let currentPro = proEle.value;
// Get the corresponding city
let currentCityList = data[currentPro];
// Clear all options in the select market
cityEle.innerHTML = ' ';
// Loop through all the markets and place them in the second SELECT tag
for (let i=0; i<currentCityList.length; i++){let currentCity = currentCityList[i];
// Create the option tag
let opEle = document.createElement('option');
// Set the text
opEle.innerText = currentCity;
/ / set the value
opEle.value = currentCity;
// Place the option tag in the second select
cityEle.appendChild(opEle)
}
}
</script>
</body>
Copy the code
conclusion
The article was first published on the wechat public account Program Yuan Xiaozhuang, and synchronized with nuggets and Zhihu.
The code word is not easy, reprint please explain the source, pass by the little friends of the lovely little finger point like and then go (╹▽╹)