BOM and DOM manipulation

First, father and son page communication

  • Communication between the main page and subpages by pop JS code

Two, window objects

  • 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()it can be abbreviated document.write()to: . (BOM and DOM operations following after writing window are omitted)
  • window object, most browsers support the window object, he said the browser window.
  • BOM and DOM operations are operated by the window object.

Common method 1. window object

(1)window.open()

  • Open a new window

(2)window.close()

  • Close the current window

2. window child objects

  • window object is the child window omitted this key does not write directly to the object out of the window to the point of beginning these objects.

Three, BOM operation

  • BOM (Browser Object Model) refers to the browser object model that enables JavaScript capable browser to "talk"
  • It is to operate the browser window

1. BOM common operation method

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

(2) screen objects

  • Screen objects, is not commonly used

(3) history objects

//相当于浏览器的后退和前进

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

(4) location objects

  • window.location object is used to get the address (URL) of the current page, and the browser is redirected to the new page.
location.href  获取URL
location.href="URL" // 跳转到指定页面
location.reload() 重新加载页面

(5) pop-up box

  • Three can be created in JS message box: alert box, check box, balloon

    1. 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("你看到了吗?");
    1. Confirmation box
    • 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("你确定吗?")
    1. Tip box
    • 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.

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

(6) 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. Similar in pythontime.sleep()
  1. setTimeout() (Set wait time)

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

    • setTimeout()The first parameter is a string containing the JavaScript statements. This statement may be as alert('5 seconds!'), or calls to functions, 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).

  2. clearTimeout()(Cancel setTimeout()setting)

    • grammar:

      clearTimeout(set)
    • Examples

      // 在指定时间即3秒之后执行一次相应函数
      var timer = setTimeout(function(){alert(123);}, 3000)
      
      // 取消setTimeout设置,只要有这个语句,上面的语句一次也不执行
      clearTimeout(timer);
  3. setInterval() (Periodic execution code)

    • setInterval()Method at a specified interval (in milliseconds) to the calling function or calculation expression.
    • setInterval()The method will keep calling function until clearInterval()being called or window is closed. By the setInterval()ID value may be used as return clearInterval()parameters of the method.

    • grammar

      setInterval("JS语句",时间间隔)  //时间间隔也是毫秒单位
    • return value

      • A can be passed to Window.clearInterval()thereby canceling the value of the code executed periodically.
  4. clearInterval()(Canceled setInterval() 的周期性执行代码)

  • clearInterval()Parameters of the method must setInterval()return the value of ID

  • grammar

    clearInterval(setInterval返回的ID值)
  • Examples

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

Four, DOM operations

  • DOM (Document Object Model) is a set of methods for the content of the document and abstract conceptualization. Which means the document object model, through which you can access all the elements of an HTML document
  • 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.
  • As long as there is a node, you can find all the other nodes.

1. DOM role

(1) DOM standard HTML document for each component is one 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) 

(2) 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

2. Find label

(1) direct Find

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

(2) Indirect Find

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

3. Node Operation

(1) create a node

  • grammar

    createElement(标签名)
  • Examples

    // 在body标签中创建一个div标签
    var divEle = document.createElement("div");

(2) adding a node

  1. Append a child node (a child node as the last)
  • appendChild(添加的子节点)
  1. The node is added into the front of a node
  • insertBefore(添加的子节点 , 某个已存在的节点)

Example:

// 创建一个img标签
var imgEle=document.createElement("img");
// 给img标签添加src属性
imgEle.setAttribute("src", "http://image11.m1905.cn/uploadfile/s2010/0205/20100205083613178.jpg");

// 给id值为 d1 的标签最后位置添加一个 img 子标签
var d1Ele = document.getElementById("d1");
d1Ele.appendChild(imgEle);

(3) remove nodes

  • grammar:
    1. Gets the element you want to delete, which deletes the parent element by calling
    2. removeChild(要删除的节点)

(4) replacement node

  • grammar:

    replaceChild(新的节点, 某个已存在的节点)

(5) Properties node

  1. Gets the value of the text node

    var divEle = document.getElementById("d1")
    divEle.innerText  // 只获取标签的文本信息  inner 是“内部的”的意思
    divEle.innerHTML  // 获取标签所有文本的信息和标签的信息
  2. Value of the text node

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

    var divEle = document.getElementById("d1");
    // 添加属性
    divEle.setAttribute("age","18") 
    // 获取属性值
    divEle.getAttribute("age")
    // 删除属性
    divEle.removeAttribute("age")

(6) Get input values ​​of the input block and the column selection

  • Labels applied to:input/select/textarea

  • grammar

    标签对象.value

(7) class of operation

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

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

(8) specifies the CSS operation

  • JS CSS property law operation

    1. For no 中横线 即 -CSS properties, generally used directly style.属性名to

      Example:

      obj.style.margin
      obj.style.width
      obj.style.left
      obj.style.position
    2. Containing 中横线 即 -CSS property, the first letter of the property into the back of the horizontal line can be capitalized.

      Example:

      obj.style.marginTop        //  原来的写法 :margin-top
      obj.style.borderLeftWidth  //  原来的写法 :border-feft-width
      obj.style.zIndex   // 原来的写法:z-index
      obj.style.fontFamily   //  原来的写法 :font-famliy

4. Event

  • Event is an action or response to satisfy certain conditions are triggered automatically, such as click a button to bring up a new content.

(1) Common events

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

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

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

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

(2) binding way

  1. One way: (not recommended)
<button onclick="func()">按钮</button>
  1. Second way: (recommended)
function func() {
            alert('我被点击了')
            }
            var i1Ele = document.getElementById('d1');
            i1Ele.onclick = function () {
                // i1Ele标签被点击之后 你能做的事
                func()
            }
  1. According to the different style and different ways of placing the label binding position, js code may run first case and an error will occur.
  • Solution one: (not recommended)
    • Use the head tag window.onload()methodological reasons, its role is to re-label head execution style tag after the body tag waiting for the code is loaded, but this time, the error will bind a way, this is not a recommended way of binding .
  • Solution two: (recommended)
    • Js code to write directly to the bottom of the body, that is the style tag placed in the body tag at the bottom.

Examples (3) events

  • Timer instance
<!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>

定时器示例
  • Search examples
<!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>

select联动

Guess you like

Origin www.cnblogs.com/Mcoming/p/11884732.html