04. The front end of the BOM 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 ().

GOOD

window object

  img

  See the example above you will find, name the package directly to the window object, look at it.

  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 (to know). *

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

  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 methods :( Window these input methods the following properties or debugger browser inside the console, the corresponding effect can see)

  • 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.open can only be closed with the js () to open the page, look on the line)

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   // 浏览器运行所在的操作系统

    See Example:

img

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, can simply be used to move forward or backward a page.

history.forward()  // 前进一页,其实也是window的属性,window.history.forward()
history.back()  // 后退一页

    img

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() 重新加载页面,就是刷新一下页面

    img

  

  The above content we need to remember is:

    1.window objects

    2.window sub-objects: location of those few properties and methods

    3. Other as understanding

  Here we come to learn some useful content more interesting:

pop-up windows

    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("你看到了吗?");

    img

  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("你确定吗?")

    img

          img

    We can return to the true and false to determine what, then use the location to jump to the corresponding website based on this value.

  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, then return the default value is the second argument, if there is no default value is returned null.

    grammar:

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

img

    It can be determined by user input to how we operate behind

  In addition to the alert box (with not all), others are rarely used, more ugly, look at the line

Timing-related (more important)

    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 () after a period of time to do something

      grammar:

var t=setTimeout("JS语句",毫秒)  第一个参数js语句多数是写一个函数,不然一般的js语句到这里就直接执行了,先用函数封装一下,返回值t其实就是一个id值(浏览器给你自动分配的)

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

      img

    clearTimeout()

      grammar:

clearTimeout(setTimeout_variable)

    For example :

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

    setInterval () from time to time to do something

      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 (mouse click, mouse movement events, etc.) for all events page

Find label (and css, like, you want to operate a label need to find it)

Direct Find

document.getElementById           根据ID获取一个标签
document.getElementsByClassName   根据class属性获取(可以获取多个元素,所以返回的是一个数组)
document.getElementsByTagName     根据标签名获取标签合集

    example: 

     img

Indirect Find

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

    img

   Find out if the content is an array, then you can take the corresponding label objects by index

    img

  Find these methods label said above, since we rarely use, and so learn JQuery, there will be very easy to use and more comprehensive search function labels, above all of these exercises look simple, there was an understanding on the line.

Node operation

Create a node (that is, create a label)

      grammar:

      createElement (name tag)

      Example:

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

     img

     img

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

    img

Delete Node

      grammar:

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

      somenode.removeChild (node ​​to be removed)

Replacement Node

      grammar:

      somenode.replaceChild (newnode, a node);

      somenode is the parent tab, then find the parent tag inside the sub-tab to be replaced, and then use the new label to replace the sub-tag

Attribute nodes

      Gets the value of the text node:

var divEle = document.getElementById("d1")
divEle.innerText  #输入这个指令,一执行就能获取该标签和内部所有标签的文本内容
divEle.innerHTML  #获取的是该标签内的所有内容,包括文本和标签

      img

      img

      The text value of the node:

var divEle = document.getElementById("d1")
divEle.innerText="1"  
divEle.innerHTML="<p>2</p>" #能识别成一个p标签

      attribute operation

var divEle = document.getElementById("d1");
divEle.setAttribute("age","18")  #比较规范的写法
divEle.getAttribute("age")
divEle.removeAttribute("age")

// 自带的属性还可以直接.属性名来获取和设置,如果是你自定义的属性,是不能通过.来获取属性值的
imgEle.src
imgEle.src="..."

Gets the value of the operation

      grammar:

      elementNode.value

      It applies to the following tag, user input or select the type of label:

      1.input

      2.select

      3.textarea

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

       For example: There are three tabs on the following page

       img

      img

      

      img

class action

className  获取所有样式类名(字符串)首先获取标签对象
标签对象.classList.remove(cls)  删除指定类
classList.add(cls)  添加类classList.contains(cls)  存在返回true,否则返回falseclassList.toggle(cls)  存在就删除,否则添加,toggle的意思是切换,有了就给你删除,如果没有就给你加一个

      For example: I want to c2 classes added class to go inside

        img

        img

      

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, in the first horizontal line made uppercase letter after the can. Such as:

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

        img

  We modify the style mentioned above, these methods should not be used in certain operations of users ah, if you are a user clicks on an item, it becomes the color change and the like, to the user or to indicate some nice effects the effect ah, so it will be with the next event we have to learn to combine things to do, events + is achieved by modifying the above style.

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 (to speak about onfocus, onblur, onclick, onchange it, other Turning back ~ ~)

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

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

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

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

Binding way:

    :( a way not often used, and the majority with the second approach)

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

    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 () {   //console.log(this)
    this.innerText="呵呵"; #哪个标签触发的这个事件,this就指向谁
  }
</script>

    Attention to a problem:

      img

      img

      img

      Another solution is to write the script tag to the bottom of the body tag

      img

      

    Example binding event timer, input time dynamic display frame which:

<!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>定时器</title>
  <script>  //当js代码中有找标签的操作的时候,别忘了页面加载的时候的顺序,以防出现找不到标签的情况出现,我们可以将这个script标签放到body标签最下面,或者用window.onload,这里我没有放,你们练习的时候放到下面去
    var intervalId; //用来保存定时器对象,因为开始定时器是一个函数,结束定时器是一个函数,两个函数都是操作的一个定时器,让他们互相能够操作这个定时器,就需要一个全局变量来接受一下这个对象
      //把当前事件放到id为i1的input标签里面
    function f() {
      var timeStr = (new Date()).toLocaleString(); // 1.拿到当前事件
      var inputEle = document.getElementById("i1");// 2.获取input标签对象
      inputEle.value = timeStr;  //3.将事件赋值给input标签的value属性
    }
  //开始定时任务
    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="开始" id="start" onclick="start();">
<input type="button" value="结束" id="end" onclick="end();">
</body>
</html>

    Examples of events:

      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(){  //如果在标签中写的blur()等方法,没有传入this参数,那么我们就需要自己来获取一下这个标签,例如下面的getElementById('d1')
    var inputEle=document.getElementById("d1");
    if (inputEle.value==="请输入关键字"){
        inputEle.value="";     //inputEle.setAttribute('value','')
    }
}

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

      select Linkage: Select province, automatically lists all the cities, for example: Selection of Hebei to show all City of Hebei Province

<!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");
  //页面一刷新就将所有的省份都添加到select标签中
  for (var i in data) {
    var optionP = document.createElement("option"); //创建option标签
    optionP.innerHTML = i; //将省份的数据添加到option标签中
    p.appendChild(optionP);//将option标签添加到select标签中
  }  //只要select中选择的值发生变化的时候,就可以触发一个onchange事件,那么我们就可以通过这个事件来完成select标签联动
  p.onchange = function () {    //1.获取省的值
    var pro = (this.options[this.selectedIndex]).innerHTML;//this.selectedIndex是当前选择的option标签的索引位置,this.options是获取所有的option标签,通过索引拿到当前选择的option标签对象,然后.innerHTML获取对象中的内容,也就是省份
    //还可以这样获取省:var pro = this.value;    var citys = data[pro]; //2. 通过上面获得的省份去data里面取出该省对应的所有的市
    // 3. 清空option
    c.innerHTML = ""; //清空显示市的那个select标签里面的内容
      //4.循环所有的市,然后添加到显示市的那个select标签中
    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>

  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: .onload () function exists to cover the phenomenon.

Guess you like

Origin www.cnblogs.com/changxin7/p/11511738.html