Environment construction of JavaScript
Development environment: webstorm, hbulider
Running environment: chrome browser
code
Knowledge 1
Several ways of writing JavaScript
1
2
3
4. Realize the display of data in the page
5 prompt Popup
5. Define variables
// var a =1; global variable // var a =1; // alert(typeof (a)) // const defines constants const pi = 3.12 console.log(pi) For this reason, we generally use let
6. Implement simple algorithm
(the same applies to logical operators & &, |,!, and comparison operators <, >, =)
6. Judgment statement
parseInt//The data type is converted to an integer, but does not include a string parsefloat//Convert Bookstore type to floating point type
Knowledge 2
Functions of JavaScript:
1. Data verification
2. Web page features
3. Data interaction
4. Back end programming (Node)
Knowledge 3
Dialog box provided by JavaScript
1. Warning box: alert (string)
2. Confirmation box: windows
Knowledge 4
Function:
function name [formal parameter list]{
//Function body
//Return return value;
}
Function name [argument list]
// function show(msg,name) { // alert(` my name is ${name},${msg} ') // // } // show("123","2334") // function add(x,y) { // return x+y; // // // } // let a = add(2,3) // alert(a) // Anonymous function let a= function () { alert("Anonymous function") } function aa(a,10)
Knowledge 5
Array array
It must be noted that js array is not the concept of array in java. It is similar to linklist in java. The bottom layer uses a two-way linked list structure
// //How to define an array // let arr = new Array() // console.log(arr) // arr.push(10) // arr.push(100) // arr.push(1000) // //Values can be assigned using subscripts // arr[4]=1000; // console.log(arr) // arr[10]= '123' //When defined, the given size // let arr2 = new Array(10); // arr2.push(100) // console.log(arr2) //You can give a value when creating an array // let arr3 = new Array(1,2,3,"1223","22","233"); // console.log(arr3) //You can do the same // let arr4 = [1,2,3] // console.log(arr4) //Traversal of array // let arr = new Array(1,2,3,4) // for (let i =0;i<arr.length;++i) { // console.log(arr[i]) // } //*Note: when using the for in structure array in JavaScript to iterate, each value iterated out is a subscript * if the iterated object is an object, the iterated out is the attribute of the object // function say() { alert(this.age) } let obj = new Object(); obj.name = "123" obj['age'] = 16; obj.say = say;//Function object for (p in obj) { console.log(p) }
Supplement:
//Array mode of es6 let arr3 = new Array(1,2,3,"1223","22","233"); for (i of arr3) { console.log(i) } arr3.forEach(function (item,key) { console.log(item,key) })
Knowledge 6
character string
//1. For the creation of string, if the characteristics of data, the type of variable is determined by the value // let s ="this is a string" // console.info(typeof (s)) //2.JavaScript provides a built-in class, stiring. Here, an object is created // let s = new String("this is a string") // console.log(typeof s) //3. Do not use the new keyword let s =String('abc') // console.info(s) //Gets the length of the string // console.log(s.length) // console.info(s[0]) // console.log(s.substr(0,1)) console.info(s.toUpperCase())//Uppercase conversion console.info(s.toLowerCase())//a lowercase letter //Traversal string // for (i in s) { // console.info(s[i]) // }
Use of Math functions
console.log(Math.E) console.log(Math.PI )//PI //ceil takes an integer up and floor takes an integer down console.log(Math.ceil(5.6)) console.log(Math.ceil(5.06)) console.log(Math.floor(5.06)) console.log(Math.floor(5.06)) console.log(Math.max(5,9)) console.log(Math.random()*10)//Take a random number, which will be a decimal, so you can use parseInt to take an integer console.log(Math.round(5.06))//rounding
Use of setInterval
function msg() { alert("3 Seconds later, I bounced out") } setInterval(msg,3000); // clearInterval(timer) / / clear data
BOM and DOM programming:
js provides a set of corresponding API s through which developers can realize various operations (open, close, refresh and reset) on the browser
windows object
js of mobile browser is not applicable to Google, but only to IE
<button onclick="closeWin();">Click to close the browser</button> <button onclick="moveWin();">Mobile browser</button> <button onclick="moveWin2();">Mobile browser</button> <button onclick="openWin();">Open a new window</button> <button onclick="goTop();" style="position: fixed; right: 30px; bottom: 30px;">Back to the top</button> <script> // console.info(this) function goTop() { window.scrollTo(0, 0);//Jump } function closeWin() { if (window.confirm("Are you sure you want to close the browser?")) { window.close(); } } function moveWin() { window.moveTo(100, 200); } function moveWin2() { window.moveBy(100, 200); } function openWin() { // window.open("http://www.baidu.com", "_blank", "toolbar=yes") window.open("http://www.baidu.com", "_blank"); }
History object (a child object of windows, which is mainly responsible for the history of the browser)
// Represents the number of times the page has been opened console.log(window.history.length); function myBack() { // history.back(); // go function /** * If the parameter is 0, it means no jump * If it is a positive number, it means to move forward. What number means to move forward * A negative number is the opposite, indicating a retreat */ history.go(-1); } function forward() { history.forward(); // history.go(1); } </script> </head> <body> <button onclick="forward();">forward</button> <button onclick="myBack();">back off</button> <a href="test.html">Next page</a> </body>
Get screen length and width
console.log(screen.height) console.log(screen.width) console.log(screen.availWidth) console.log(screen.availHeight) // The effective height removes the height of the bottom taskbar
Get computer information (navigator)
// Kernel information obtained console.info(window.navigator.platform) console.info(navigator.platform) // Returns the code name of the browser console.info(window.navigator.cookieEnabled) // Returns a Boolean value indicating whether cookie s are enabled in the browser console.info(window.navigator.appVersion) // Returns the platform and version information of the browser console.info(window.navigator.appCodeName) // Returns the code name of the browser Mozilla // Positioning longitude and latitude with Google Maps // console.info(window.navigator.geolocation) // User agent object // console.info(navigator.userAgent)
location object
// Refresh page // setTimeout(function () { // window.location.reload(); // }, 5000);
// Common properties console.info(location.href) /*Get the website*/ console.info(location.protocol) /*agreement*/ console.info(location.port)/*port*/ console.info(location.hostname)/*host*/ console.info(location.host)/*Host plus port*/ console.info(location.pathname)/*url*/ console.info(location.hash)/**/ console.info(location.search)/*In order to get the code behind the web address Hello, the purpose is to refresh the page*/ function openWin() { window.location.href = "http://www.baidu.com"; } function openWin2() { window.location.href.replace("04.location object.html", "01.history object.html") }
document object
// 1. It is absolutely forbidden to directly use the id operation label // console.log(box) // box.innerHTML = "I modified this content"; // 2. document.getElementById gets the DOM object by id // let box = document.getElementById("box"); // console.log(box); // 3. Get a set of tags using the class name // What you get through className is a set of tags, which is a collection similar to an array // Therefore, if you want to operate the DOM object inside, you need to take it out (subscript) for processing // let boxs = document.getElementsByClassName("box"); // console.info(boxs) // boxs[4].innerHTML = "I modified this content"; // 4. Get the required label group by label name // var divs = document.getElementsByTagName("div"); // console.info(divs); // 5. Get the DOM object through the name attribute // This is usually what form labels need to use // var boxs = document.getElementsByName("box"); // console.info(boxs); // boxs[0].checked = true; // 6. ES5 two new API s at the same time // querySelector can only get one DOM object, so it usually uses the same id // let box = document.querySelector("#box"); // let box = document.querySelector(".box"); // console.info(box) // Box. InnerHTML = ` < H1 > this tag < / H1 >` // let boxs = document.querySelectorAll(".box"); // console.info(boxs) // for (box of boxs){ // Box. InnerHTML = ` < H1 > this tag < / H1 > `; // }
Operation of DOM properties
let box = document.getElementById("box"); // box.title = "this is my new title"; // box.style.color = "red"; // box["title"] = "set in array mode" // getAttribute setAttribute() var s = box.getAttribute("aa"); console.info(s) // class recommends passing className // box.className = "box"; // The following is not recommended // box.setAttribute("class", "box");
DOM events get data and how to change it
<style type="text/css"> #show { height: 300px; border: 1px solid red; } </style> </head> <body> <div style="width: 300px;" id="show" onclick="scale()">This is a div</div> <script> var _show = document.getElementById("show"); // 1. The first method: DOM object. style. This method can only obtain inline styles //You can only get the width in the style, not the height. What should be set for the height belongs to the in-line style console.log(_show.style.width); console.log(_show.style.height); // 2. The second method, w3c specifies how to obtain the style value console.log(getComputedStyle(_show).height) console.info(getComputedStyle(_show).width) function scale() { var _show = document.getElementById("show"); // Obtain the width and height. The data obtained here is with "px" var h = getComputedStyle(_show).height; var w = getComputedStyle(_show).width; console.info(h, w) // Because the unit is a string, it needs to be removed first. After the operation is completed, the unit is spliced _show.style.height = parseInt(h) + 10 + "px"; _show.style.width = parseInt(w) + 10 + "px"; // Get width and height, only in line styles can be obtained //offset is to obtain pure data without pixels, which is equivalent to the value console.log(_show.offsetHeight, _show.offsetWidth) console.log(_show.clientHeight, _show.clientWidth) _show.style.height = _show.offsetHeight + 10 + "px"; _show.style.width = _show.offsetWidth + 10 + "px"; } </script>
Implementation of lucky draw cases
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Welcome to the lucky draw</title> <style> .box { width: 800px; height: 800px; border: 1px solid red; margin: auto; text-align: center; } .box > div { width: 300px; height: 300px; background-color: #4c8174; border-radius: 50%; margin: auto; line-height: 300px; color: white; font-size: 30px; font-weight: bold; /*margin-top: 50px;*/ } .box > a { text-decoration: none; font-size: 20px; display: inline-block; background-image: linear-gradient(to right, skyblue, #4c8174); width: 200px; height: 50px; border-radius: 20px; line-height: 50px; color: white; margin: 30px; } .bg-red { background-color: red !important; /*important Set the weight and let him use it first*/ } .bg-primary { background-color: #8A2BE2 !important; } .bg-success { background-color: green !important; } </style> </head> <body> <div class="box"> <div id="content">prize</div> <a href="#"Id =" start "onclick =" run(); "> start lottery</a> </div> <script !src=""> /*The principle is that random goods will jump when the lottery starts, and the random function is not used when the lottery stops*/ // Define an array const goods = ["iphone13 MAX", "BMW 5", "One computer", "notebook", "pen", "Router", "java Course coupon", "doll", "A bowl of beef noodles", "National Day 7 Tour"]; let flag = true;/*boolean Value control*/ let content = document.getElementById("content"); let start = document.querySelector("#start"); let timer;/*Set the global variable so that the following functions can use this variable*/ let index; function run() { if (flag) { flag = false; start.innerText = "Stop the lottery"; // content.className = "bg-red"; content.style.background = "yellow" //Set the loop function to randomly extract the goods timer = window.setInterval(function () { index = Math.floor(Math.random() * goods.length);/*Take a value at random and take an integer down*/ let g = goods[index];/*Obtain the data of each prize through subscript*/ content.textContent = g;/*Function to get product data*/ }, 10); } else { flag = true; start.innerText = "Start the lottery"; content.className = "bg-primary";/*Get data style*/ window.clearInterval(timer); } } </script> </body> </html>
event
Three elements of event: event source, event object and event handler
How does Js handle events
1. Directly use onxxx to bind events. Normally, this keyword points to windows objects
2. If you want to handle complex events, it is recommended to obtain DOM objects through object binding
dom object. xxx = func
this represents the event object itself
Benefits: 1. Realize three-tier separation, and disconnect the direct binding relationship between html and js. 2
2. You can get the event object directly
3. Event monitoring
Specify the flow mode of event flow (bubble flow, capture flow)