BOM operating DOM manipulation

BOM operation


(B refers to the browser)

BOM(Browser Object Model)是指浏览器对象模型,它使 JavaScript 有能力与浏览器进行“对话”。

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

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

Example:

<script>
    function func(){
        window.close()  # 窗口关闭
    }
    var t = setTimeout(func,3000);  #设置关闭时间,为3秒
    clearTimeout(t)  # 然而这一步清空了关闭时间的设置,所以界面不会关闭
</script>

No effect unless commented clearTimeout (t), to perform three seconds after closing the window function

<script>
    function foo() {
        alert(123)  # 显示警告,内容:123
    }
    function show() {
        var t = setInterval(foo,3000);  # 每隔三秒钟执行foo函数
        function inner(){
            clearInterval(t)  # inner函数 和上面clearTimeout类似,清除了时间设定
        }
        setTimeout(inner,9000)  # 设置了结束时间为9秒,在结束时间之前执行inner函数
    }
    show()
</script>

Effect: pop-pop three seconds, and never again pop up

DOM manipulation


(D refer to that document, which is document) (Important)

DOM(Document Object Model)是一套对文档的内容进行抽象和概念化的方法。

当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。

HTML DOM 模型被构造为对象的树。

HTML DOM tree

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

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

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

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

For the following tags:

  • .input
  • .select
  • .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);

class action

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

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

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

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

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

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

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

Binding way:

method one:

<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 () {
    this.innerText="呵呵";
  }
</script>

Start time, end

<!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>

Get value in the input

<!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>

After selecting the province, the next column shows the corresponding city

<!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>

jQuery


jQuery

// 模态框实例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jQuery-3.4.1.js"></script>
    <style>
        .cover {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-color: rgba(128,128,128,0.45);
            z-index: 9;
        }
        .modal {
            position: fixed;
            top: 50%;
            left: 50%;
            height: 200px;
            width: 400px;
            background-color: white;
            z-index: 10;
            margin-top: -100px;
            margin-left: -200px;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
<div class="c1">
    我是被压在最下的
</div>
<button class="c2">叫人</button>
<div class="cover hidden"></div>
<div class="modal hidden">
    <p>username:<input type="text"></p>
    <p>password:<input type="text"></p>

    <button class="cancel">取消</button>
</div>

<script>
    var b1Ele = $('.c2')[0];
    b1Ele.onclick = function () {
        // 将纱布和白框的hidden类属性移除
        $('.cover').removeClass('hidden');  // xxx.classList.remove('hidden')
        $('.modal').removeClass('hidden')
    };
    var cancelEle = $('.cancel')[0];
    cancelEle.onclick = function () {
        $('.cover').addClass('hidden');  // xxx.classList.add('hidden')
        $('.modal').addClass('hidden')
    }
</script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/PowerTips/p/11494951.html