Article From:https://www.cnblogs.com/Dominic-Ji/p/9121560.html

The BOM and DOM of the front-end base

 

Foreplay

So far, we have learned some simple grammar of JavaScript. But these simple syntax do not have any interaction with the browser.

That is to say, we can not make some interactions with web pages that we often see. We need to continue to learn about BOM and DOM.

JavaScriptIt is divided into ECMAScript, DOM, BOM.

 

BOM(Browser Object Model)It refers to browser object model, which enables JavaScript to have “dialogue” with browsers.

DOM (Document Object Model)It refers to the document object model, through which all elements of the HTML document can be accessed.

 

WindowThe object is one of the highest level object of the client JavaScript, and because the window object is the common ancestor of most other objects, the reference of the window object can be omitted when the methods and properties of the window object are called. For example: window.documenT.write () can be simply written as: document.write ().

windowobject

All browsers support window objects. It represents the browser window.

*If the document contains the framework (frame or iframe tags), the browser creates an window object for the HTML document and creates an additional window object for each framework.

*No public standards are applied to window objects, but all browsers support that object.

All JavaScript global objects, functions, and variables automatically become members of the window object.

The global variable is the attribute of the window object. The global function is the method of the window object.

Next, the document of HTML DOM is also one of the attributes of window objects.

Some commonly used Window methods:

  • window.innerHeight – The internal height of the browser window
  • window.innerWidth – The internal width of the browser window
  • window.open() – Open a new window
  • window.close() – Close the current window

windowSubobject

navigatorObject (understand)

Browser object, through this object can determine the browser used by users, including browser related information.

navigator.appName  // WebFull name of browsers
navigator.appVersion  // WebBrowser vendor and version of the detailed string
navigator.userAgent  // The vast majority of the information on the client side
navigator.platform   // The operating system in which the browser runs

screenObject (understand)

Screen objects, not commonly used.

Some attributes:

  • screen.availWidth – Available screen width
  • screen.availHeight – Available screen height

historyObject (understand)

window.history The object contains the history of the browser.

Browse the history object, including the user’s browsing history of the current page, but we can not see the specific address, can simply be used to advance or back a page.

history.forward()  // Advance a page
history.back()  // Back a page

locationobject

window.location The object is used to get the address of the current page (URL) and redirect the browser to the new page.

Common attributes and methods:

location.href  Get URLLocation.href="URL" // Jump to the specified pageLocation.reload () reload the page

Popup

You can create three message boxes in JavaScript: warning box, confirmation box, prompt box.

Warning box

Warning boxes are often used to ensure that users can get certain information.

When the warning box appears, the user needs to click the confirmation button to continue the operation.

Grammar:

alert("Did you see it? ");

Confirmation box (understand it)

The confirmation box is used to enable users to verify or accept certain information.

When the confirmation box appears, the user needs to click the confirm or cancel button to continue the operation.

If the user clicks the confirmation, the return value is true. If the user clicks cancel, the return value is false.

Grammar:

confirm("Are you sure? ")

Prompt box (understand)

The prompt box is often used to prompt users to enter a value before entering the page.

When the prompt box appears, the user needs to enter a value, then click the confirmation or cancel button to continue the operation.

If the user clicks confirmation, then the value returned is the value entered. If the user clicks cancel, the return value is null.

Grammar:

prompt("Please input "," your answer at the bottom.

Timing correlation

By using JavaScript, we can execute code at a certain time interval rather than immediately after the function is invoked. We call it a chronograph.

setTimeout()

Grammar:

var t=setTimeout("JSStatement ", milliseconds")

setTimeout() The method returns a value. In the above statement, the value is stored in the variable named t. If you want to cancel this setTimeout (), you can use this variable name to specify it.

setTimeout() The first parameter is a string containing JavaScript statements. This statement may be like “alert (‘5 seconds!”), or call to function, such as alertMsg ().

The second parameter indicates how many milliseconds from the current time to execute the first parameter (1000 milliseconds equal to one second).

clearTimeout()

Grammar:

clearTimeout(setTimeout_variable)

For instance

// Execute a corresponding function after a specified time
var timer = setTimeout(function(){alert(123);}, 3000)
// Cancel the setTimeout settings
clearTimeout(timer);

setInterval()

setInterval() Method can call functions or compute expressions according to specified cycles (milliseconds).

setInterval() The method calls the function continuously until clearInterval () is invoked or the window is closed. The ID value returned by setInterval () can be used as the parameter of the clearInterval () method.

Grammar:

setInterval("JSStatement ", time interval)

Return value

A value that can be passed to Window.clearInterval () to cancel periodic execution of code.

clearInterval()

clearInterval() Method can cancel the timeout set by setInterval ().

clearInterval() The parameter of the method must be the ID value returned by setInterval ().

Grammar:

clearInterval(setintervalThe returned ID value)

For instance:

// A corresponding function is executed every other time
var timer = setInterval(function(){console.log(123);}, 3000)
// Cancel the setInterval settings
clearInterval(timer);

A slightly larger example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>timer</title>
  <script>
    var intervalId;

    function f() {
      var timeStr = (new Date()).toLocaleString();
      var inputEle = document.getElementById("i1");
      inputEle.value = timeStr;
    }

    function start() {
      f();
      if (intervalId === undefined) {
        intervalId = setInterval(f, 1000);
      }
    }
    function end() {
      clearInterval(intervalId);
      intervalId = undefined;
    }

  </script>
</head>
<body>

<input type="text" id="i1">
<input type="button" value="Start " id="start" onclick="start();">
<input type="button" value="End " id="end" onclick="end();">
</body>
</html>

Timer example

DOM

DOM(Document Object Model)It is a set of methods to abstract and conceptualize the contents of documents. It

When the web page is loaded, the browser creates the Document Object Model of the page.

HTML DOM The model is constructed as the tree of the object.

HTML DOM tree

DOMThe standard specifies that each component in the HTML document is a node (node):

  • Document node (document object): representing the entire document
  • Element node (element object): represents an element (label).
  • Text node (text object): represents the text in the element (label).
  • Attribute node (attribute object): represents an attribute, and the element (label) has properties.
  • Annotation is the annotated node (comment object) 

JavaScript A dynamic HTML can be created through DOM:

  • JavaScript Can change all HTML elements in the page
  • JavaScript Can change all HTML properties in the page
  • JavaScript Can change all CSS styles in the page
  • JavaScript Can respond to all events in a page

Lookup label

Direct lookup

document.getElementById           Get a label based on IDDocument.getElementsByClassName is acquired according to class attribute.Document.getElementsByTagName gets labels based on tag names.Aggregation

Be careful:

Where does the JS code involving the DOM operation should be placed in the document?

Indirect lookup

Copy code
parentElement            Parent node label elementAll sublabels of childrenFirstElementChild first sub label elementLastElementChild finalA sub label elementNextElementSibling next brother tag elementPreviousElementSibling a brother tag element
Copy code

Node operation

Create a node

Grammar:

createElement(Label name)

Examples:

var divEle = document.createElement("div");

Add node

Grammar:

Append a child node (as the last child node)

somenode.appendChild(newnode);

Put the added node to the front of a node.

somenode.insertBefore(newnode,A node);

Examples:

var imgEle=document.createElement("img");
imgEle.setAttribute("src", "http://image11.m1905.cn/uploadfile/s2010/0205/20100205083613178.jpg");
var d1Ele = document.getElementById("d1");
d1Ele.appendChild(imgEle);

Delete nodes:

Grammar:

Gets the elements to be deleted, and is deleted by calling the parent element.

removeChild(Nodes to be deleted.)

Replacement nodes:

Grammar:

somenode.replaceChild(newnode, A node);

Attribute node

Get the value of the text node:

var divEle = document.getElementById("d1")
divEle.innerText
divEle.innerHTML

Setting the value of the text node:

var divEle = document.getElementById("d1")
divEle.innerText="1"
divEle.innerHTML="<p>2</p>"

attributeoperation

Copy code
var divEle = document.getElementById("d1");
divEle.setAttribute("age","18")
divEle.getAttribute("age")
divEle.removeAttribute("age")

// The attributes you own can also be directly obtained and set by the attribute names.
imgEle.src
imgEle.src="..."
Copy code

Gain value operation

Grammar:

elementNode.value

Applicable to the following label:

  • .input   
  • .select
  • .textarea 
Copy code
var iEle = document.getElementById("i1");
console.log(iEle.value);
var sEle = document.getElementById("s1");
console.log(sEle.value);
var tEle = document.getElementById("t1");
console.log(tEle.value);
Copy code

classOperation

Copy code
className  Get all of the style class names (strings)
classList.remove(cls) Delete the specified classClassList.add (CLS) add class
classList.contains(cls) Return to true, otherwise return to false
classList.toggle(cls) The existence is deleted, otherwise add
Copy code

Specify the CSS operation

obj.style.backgroundColor="red"

JSThe law of operating the CSS property:

1.The style. attribute name is usually used directly for the CSS attribute without the middle line. Such as:

obj.style.margin
obj.style.width
obj.style.left
obj.style.position

2.For the CSS attribute that contains the middle line, change the first letter after the middle line to uppercase. Such as:

obj.style.marginTop
obj.style.borderLeftWidth
obj.style.zIndex
obj.style.fontFamily

Event

HTML 4.0 One of the new features is the ability to enable HTML events to trigger action in browsers, such as starting a JavaScript when a user clicks on a HTML element. The following is a list of attributes that can be inserted into the HTML tag to define things.A piece of action.

Common events

Copy code
onclick        Event handle called when a user clicks on an object.Ondblclick the event handle called when a user double-click on an object.The onfocus element gets the focus.// Exercise: the input box
onblur         The element loses its focus. Application scenario: for form validation, when the user leaves an input box, the representative has been typed, and we can verify it.The content of the onchang E domain is changed.Application scenario: usually used for form elements, triggering when element contents are changed. (select linkage)Onkeydown a keyboard key is pressed. Application scenario: when the user presses the enter button in the last input box,Form submission.Onkeypress a keyboard key is pressed and released.Onkeyup a keyboard is loosened.Onload a page or an image is loaded.OnmousedoThe WN mouse button is pressed.The onMouseMove mouse is moved.The onmouseout mouse moves away from an element.The OnMouseOver mouse moves over a certain element.OnselectThe text in the text box occurs when the text is selected.The onsubmit confirmation button is clicked and the object is form.
Copy code

 Binding mode:

Way 1:

Copy code
<div id="d1" onclick="changeColor(this);">I < /div>< script>function changeColor(ths) {
    ths.style.backgroundColor="green";
  }
</script>
Copy code

Be careful:

thisIs a real argument that represents the current element that triggers events.

The ths in the function definition process is the form parameter.

Mode two:

Copy code
<div id="d2">I < /div>< script>var divEle2 = document.getElementById("d2");
  divEle2.onclick=function () {
    this.innerText=""Ha ha". ";
  }
</script>
Copy code

Event examples:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            height: 200px;
            width: 200px;
            border-radius: 50%;
        }
        .bg-red {
            background-color: red;
        }
        .bg-green {
            background-color: green;
        }
    </style>
</head>
<body>

<input type="button" id="b1" value="switch" onclick="change();">

<input type="button" id="b2" value="switch">

<div class="c1 bg-red"></div>


<script>
    function change() {
        // Find the C1 label
        var c1Ele = document.getElementsByClassName("c1")[0];
        // Modify classList
        c1Ele.classList.toggle("bg-green");
    }

    // Binding events through JS code
    var b2Ele = document.getElementById("b2");

    b2Ele.onclick = ()=>{
        change();
    }
</script>
</body>
</html>

Click the event instance

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="button" id="b1" value="start">
<input type="button" id="b2" value="Stop it">
<input type="text" id="i1">

<script>

    var t;
    function showTime() {
        // Fill in the current time into I1
        var now = new Date();
        var i1Ele = document.getElementById("i1");
        i1Ele.value = now.toLocaleString();
    }
    showTime();
    // Click the start button to execute showTime once every second.// 1。Find the start button and bind it to it
    var b1Ele = document.getElementById("b1");
    b1Ele.onclick = function () {
        if (!t){
           t = setInterval(showTime, 1000);
        }
    };

    // Bind the event to the stop button, and then clear the timer after clicking.
    var b2Ele = document.getElementById("b2");
    b2Ele.onclick = function () {
        clearInterval(t);  // The timer is cleared. T is just an ordinary variable, which preserves the ID value of the timer.
        console.log(t);
        t = undefined;
    };
</script>
</body>
</html>

Timer instance

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<div id="d1">Ha ha < /div>< script>var d1Ele = document.getElementById("d1");
    console.log(d1Ele);
    d1Ele.innerText = "Ha-ha";
</script>
</body>
</html>

JSCode loading sequence problem

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="text" id="i1" value="Head and Shoulders" onfocus="f(this);">

<input type="text" id="i2" value="Spicy strip" onfocus="f(this);">


<script>

    function f(ths) {
        ths.value = "";
    }

//    // Setting up an event to get the cursor for the I1,//    var i1Ele = document.getElementById("i1");
//    i1Ele.onfocus = function () {
//        // Set your own value value as ""//        this.value = "";
//    };
//    // Binding an event to the I1 to lose the focus of the cursor//    i1Ele.onblur = function () {
//        this.value = "Head and Shoulders ";//    }
</script>
</body>
</html>

Input box instance

Copy code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The search box example < /title>< /head>< body>< input id= "D1" type= "text" value= "please input keywords" ONBLur= "blur ()" onfocus= "focus ()" ">";< script>function focus(){
    var inputEle=document.getElementById("d1");
    if (inputEle.value==="Please enter the keyword. "){
        inputEle.value="";
    }
}

function blur(){
    var inputEle=document.getElementById("d1");
    var val=inputEle.value;
    if(!val.trim()){
        inputEle.value="Please enter the keyword. ";
    }
}
</script>
</body>
</html>
Copy code

Copy code
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>selectLinkage < /title>< /head>< body>< select id= "province" >< option> please select the province: < /oPtion>< /select>< select id= "city" >< option> please choose the city: < /option>< /select>< script>
  data = {""Hebei": "Langfang", "Handan", "Beijing": "Chaoyang District", "Haidian District", "Shandong": "Weihai city", "Yantai city".]};

  var p = document.getElementById("province");
  var c = document.getElementById("city");

  for (var i in data) {
    var optionP = document.createElement("option");
    optionP.innerHTML = i;
    p.appendChild(optionP);
  }
  p.onchange = function () {
    var pro = (this.options[this.selectedIndex]).innerHTML;
    var citys = data[pro];
    // Emptying option
    c.innerHTML = "";

    for (var i=0;i<citys.length;i++) {
      var option_city = document.createElement("option");
      option_city.innerHTML = citys[i];
      c.appendChild(option_city);
    }
  }
</script>
</body>
</html>
Copy code

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *