創建並放置新的節點
- 獲取元素
// 獲取<section> var section = document.querySelector('section'); /* querySelector()調用會匹配它在文檔中遇到的第一個<section>元素。如果想對多個元素進行匹配和操作, 你可以使用Document.querySelectorAll(),這個方法匹配文檔中每個匹配選擇器的元素,並把它們的引用存儲在一個array中。 */
- 用 Document.createElement() 創建一個新的段落
var div= document.createElement('div'); div.textContent = '在section中添加div';
- 用 Node.appendChild() 方法在後面追加新的段落
section.appendChild(div);
- 用 Document.createTextNode() 創建一個文本節點,並文本節點綁定到div節點上
var text = document.createTextNode('這是文本內容'); var textDiv= document.querySelector('div'); textDiv.appendChild(text);
移動和刪除元素
- 把具有內部鏈接的段落移到sectioin的底部
section.appendChild(linkPara)
- Node.cloneNode() 方法返回調用該方法的節點的一個副本
var dupNode = node.cloneNode(deep); node:將要被克隆的節點 dupNode:克隆生成的副本節點 deep 可選:是否採用深度克隆,如果爲true,則該節點的所有後代節點也都會被克隆,如果爲false,則只克隆該節點本身.默認值變成了 false
- 刪除節點
//刪除section下的div section.removeChild(textDiv); //要刪除一個僅基於自身引用的節點 textDiv.parentNode.removeChild(textDiv);
操作樣式
- 方法一
//直接在想要動態設置樣式的元素內部添加內聯樣式。這是用HTMLElement.style屬性來實現。 textDiv.style.color = 'white'; textDiv.style.backgroundColor = 'black'; textDiv.style.padding = '10px'; textDiv.style.width = '250px'; textDiv.style.textAlign = 'center';
- 方法二 通過添加class
<style> .highlight { color: white; background-color: black; padding: 10px; width: 250px; text-align: center; } </style> <script> textDiv.setAttribute('class', 'highlight'); </script>
從Window對象中獲取信息
- 獲取這個div的引用,然後獲取視窗(顯示文檔的內部窗口)的寬度和高度, 並存入變量中 — 這兩個值包含在 Window.innerWidth 和 Window.innerHeight 屬性中
var div = document.querySelector('div'); var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight;
- 將動態地改變div的寬度和高度,使其等於視窗的寬度和高度
div.style.width = WIDTH + 'px'; div.style.height = HEIGHT + 'px';
- Window 對象有一個稱爲 resize 的可用事件。每次窗口調整大小時都會觸發該事件 — 我們可以通過 Window.onresize 事件處理程序來訪問它
window.onresize = function() { WIDTH = window.innerWidth; HEIGHT = window.innerHeight; div.style.width = WIDTH + 'px'; div.style.height = HEIGHT + 'px'; }