--BOM the front and DOM

Foreplay

So far, we've learned some simple JavaScript syntax. But these simple syntax, and browser did not have any interaction.

That is, we can not make some some interactive web we often see, we need to continue to learn BOM and DOM knowledge.

JavaScript is divided into ECMAScript, DOM, BOM.

BOM (Browser Object Model) refers to the browser object model that enables JavaScript capable browser to "talk."

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

Window object is one of the top target client JavaScript, because the window object is the common ancestor of most of the other objects, when calling window object's methods and properties, you can omit a reference to the window object. For example: window.document.write () can be abbreviated as: document.write ().

window object

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

** If the document contains a frame (frame or iframe tag), the browser will create a window object as an HTML document, and create an additional window object for each frame. *

** does not apply to public standard window object, but all browsers support the object. *

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

Global variables are window object's properties. Global function is the window object.

Then talk about the HTML DOM document window is one of the attributes of the object.

Some commonly used Window methods:

  • Internal height of the browser window - window.innerHeight
  • window.innerWidth - inside the browser window width
  • window.open () - opens a new window
  • window.close () - Close the current window

window child objects

Browser object, the object can be determined by the browser used by the user, including browser-related information.

navigator.appName  // Web浏览器全称
navigator.appVersion  // Web浏览器厂商和版本的详细字符串
navigator.userAgent  // 客户端绝大部分信息
navigator.platform   // 浏览器运行所在的操作系统

screen objects (to understand)

Screen objects, is not commonly used.

Some properties:

  • screen.availWidth - available screen width
  • screen.availHeight - available screen height

history object (to understand)

window.history object contains the browser's history.

Browsing history object that contains the user's current page browsing history, but we can not see the specific address, it can simply be used to move forward or backward a page.

history.forward()  // 前进一页
history.back()  // 后退一页

The location object

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

Common attributes and methods:

location.href  获取URL
location.href="URL" // 跳转到指定页面
location.reload() 重新加载页面

Pop-up box

Three can be created in JavaScript message box: alert box, check box, message box.

Alert box

Alert box is often used to ensure that users can get some information.

When the warning box appears, users need to click the OK button in order to proceed.

grammar:

alert("你看到了吗?");

Confirmation box (to understand)

Check box for the user to verify or receive certain information.

When the confirmation box appears, users need to click OK or Cancel button in order to proceed.

If the user clicks to confirm, the return value is true. If the user clicks Cancel, the returned value is false.

grammar:

confirm("你确定吗?")

Prompt box (to understand)

Prompt box is often used to prompt the user to input a value before entering a page.

When the prompt box appears, users need to enter a value, then click OK or Cancel button to continue to manipulate.

If the user clicks to confirm, the return value is entered. If the user clicks Cancel, the returned value is null.

grammar:

prompt("请在下方输入","你的答案")

Timing-related

By using JavaScript, we can in a certain interval of time later to execute code, and not immediately after the function is called. We call timed events.

setTimeout()

grammar:

var t=setTimeout("JS语句",毫秒)

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

The first parameter setTimeout () is a string containing a JavaScript statement. This statement may be as "alert ( '5 seconds!')", Or a call to a function, such as alertMsg () ".

The second parameter indicates a parameter from the implementation of how many milliseconds from the current (1000 ms is equal to one).

clearTimeout()

grammar:

clearTimeout(setTimeout_variable)

For example :

// 在指定时间之后执行一次相应函数
var timer = setTimeout(function(){alert(123);}, 3000)
// 取消setTimeout设置
clearTimeout(timer);

setInterval()

setInterval () method in accordance with a specified period (in milliseconds) to the calling function or calculation expression.

setInterval () method will continue to call the function, until the clearInterval () is called, or the window is closed. A setInterval () ID is used as a parameter value returns the clearInterval () method.

grammar:

setInterval("JS语句",时间间隔)

return value

Can be passed to a window.clearInterval () so as to cancel the value of the code is executed periodically.

clearInterval()

the clearInterval () method cancels the timeout setInterval () set.

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

grammar:

clearInterval(setinterval返回的ID值)

for example:

// 每隔一段时间就执行一次相应函数
var timer = setInterval(function(){console.log(123);}, 3000)
// 取消setInterval设置
clearInterval(timer);

JUDGMENT

DOM (Document Object Model) is a set of methods for the content of the document and abstract conceptualization.

When the page is loaded, the browser will create a page of a document object model (Document Object Model).

HTML DOM model is constructed as an object tree.

HTML DOM tree

img

DOM standard specifies that each component of an HTML document is a node (node):

  • Document node (document object): On behalf of the entire document
  • Element node (element object): represents an element (tag)
  • Node text (text object): Representative elements (tags) in the text
  • Node attribute (attribute objects): represents an attribute element (tag) have properties
  • Comments are comment nodes (comment Object) 

JavaScript can create dynamic HTML through DOM:

  • JavaScript can change all the HTML elements on the page
  • JavaScript can change the properties of all HTML pages
  • JavaScript can change all CSS styles page
  • JavaScript can react to all events page

Find label

Direct Find

document.getElementById           根据ID获取一个标签
document.getElementsByClassName   根据class属性获取
document.getElementsByTagName     根据标签名获取标签合集

note:

DOM operations related to the JS code should be placed in which position the document.

Indirect Find

Copy the code

Copy the code

parentElement            父节点标签元素
children                 所有子标签
firstElementChild        第一个子标签元素
lastElementChild         最后一个子标签元素
nextElementSibling       下一个兄弟标签元素
previousElementSibling   上一个兄弟标签元素

Copy the code

Copy the code

Node operation

Creating nodes

grammar:

createElement (name tag)

Example:

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

Add Nodes

grammar:

Append a child node (a child node as the last)

somenode.appendChild(newnode);

The added nodes placed in front of a node.

somenode.insertBefore (newnode, a node);

Example:

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

grammar:

Gets the element you want to delete, delete the method by calling the parent element.

somenode.removeChild (node ​​to be removed)

Replace node:

grammar:

somenode.replaceChild (newnode, a node);

Attribute nodes

Gets the value of the text node:

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

The text value of the node:

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

attribute operation

Copy the code

Copy the code

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

// 自带的属性还可以直接.属性名来获取和设置
imgEle.src
imgEle.src="..."

Copy the code

Copy the code

Gets the value of the operation

grammar:

elementNode.value

For the following tags:

  • .input
  • .select
  • .textarea

Copy the 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 the code

class action

Copy the code

className  获取所有样式类名(字符串)

classList.remove(cls)  删除指定类
classList.add(cls)  添加类
classList.contains(cls)  存在返回true,否则返回false
classList.toggle(cls)  存在就删除,否则添加

Copy the code

Specifies the CSS operation

obj.style.backgroundColor="red"

JS CSS property law operation:

1. For the CSS property not used directly in the horizontal line of the general style. Attribute name. Such as:

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

2. CSS properties contained in the horizontal line, the first letter capitalized later horizontal line can be replaced. Such as:

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

event

One of the new features of HTML 4.0 is the ability to make HTML browser event triggers the action (action), like starting a JavaScript when a user clicks on an HTML element. The following is a list of attributes that can be inserted into the HTML tags to define event actions.

Common events

Copy the code

onclick        当用户点击某个对象时调用的事件句柄。
ondblclick     当用户双击某个对象时调用的事件句柄。

onfocus        元素获得焦点。               // 练习:输入框
onblur         元素失去焦点。               应用场景:用于表单验证,用户离开某个输入框时,代表已经输入完了,我们可以对它进行验证.
onchange       域的内容被改变。             应用场景:通常用于表单元素,当元素内容被改变时触发.(select联动)

onkeydown      某个键盘按键被按下。          应用场景: 当用户在最后一个输入框按下回车按键时,表单提交.
onkeypress     某个键盘按键被按下并松开。
onkeyup        某个键盘按键被松开。
onload         一张页面或一幅图像完成加载。
onmousedown    鼠标按钮被按下。
onmousemove    鼠标被移动。
onmouseout     鼠标从某元素移开。
onmouseover    鼠标移到某元素之上。

onselect      在文本框中的文本被选中时发生。
onsubmit      确认按钮被点击,使用的对象是form。

Copy the code

Binding way:

method one:

Copy the code

Copy the code

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

Copy the code

Copy the code

note:

this is an argument that is the current element that triggered the event.

Function definition during ths as parameter.

Second way:

<div id="d2">点我</div>
<script>
  var divEle2 = document.getElementById("d2");
  divEle2.onclick=function () {
    this.innerText="呵呵";
  }
</script>

Examples of events:

Timer Example:

Copy the code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<input type="text" id="i1">
<button id="b1">开始</button>
<button id="b2">结束</button>

<script>
    var t;
    function showTime() {
        var i1Ele = document.getElementById('i1');
        var time = new Date();
        i1Ele.value = time.toLocaleString();
    }
    showTime();
    var b1Ele = document.getElementById('b1');
    b1Ele.onclick = function (ev) {
        if (!t){
            t = setInterval(showTime,1000)
        }
    };
    var b2Ele = document.getElementById('b2');
    b2Ele.onclick = function (ev) {
       clearInterval(t);
       t = undefined
    };

</script>
</body>
</html>

Copy the code

Search box example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>搜索框示例</title>

</head>
<body>
    <input id="d1" type="text" value="请输入关键字" onblur="blur()" onfocus="focus()">
    
<script>
function focus(){
    var inputEle=document.getElementById("d1");
    if (inputEle.value==="请输入关键字"){
        inputEle.value="";
    }
}

function blur(){
    var inputEle=document.getElementById("d1");
    var val=inputEle.value;
    if(!val.trim()){
        inputEle.value="请输入关键字";
    }
}
</script>
</body>
</html>

select Linkage

<!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>select联动</title>
</head>
<body>
<select id="province">
  <option>请选择省:</option>
</select>

<select id="city">
  <option>请选择市:</option>
</select>

<script>
  data = {"河北省": ["廊坊", "邯郸"], "北京": ["朝阳区", "海淀区"], "山东": ["威海市", "烟台市"]};

  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];
    // 清空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 the code

window.onload

When we bind events to elements on the page, you must wait until the document is loaded. Because we can not give binding element of a non-existent event.

window.onload event fires when the document load process ended. At this point, all objects in the document are located in the DOM, and all images, scripts, links, and sub-frames have finished loading.

Note: () function exists to cover the phenomenon .onload

Guess you like

Origin www.cnblogs.com/guyouyin123/p/12120692.html