Javascript的数据类型
- 1.BOM(浏览器对象模型)
- 1.1window对象
- (1)全局作用域:
- (2)窗口属性:
- (3)弹窗和对话框:
- (4)定时器:
- (5)导航和历史:
- (6)打开和关闭窗口:
- 1.2navigator对象
- (1)浏览器信息属性:
- (2)浏览器功能检测:
- (3)媒体功能检测:
- (4)其他属性和方法:
- 1.3location 对象
- (1)获取和设置 URL 信息:
- (2)页面导航:
- (3)操作浏览历史:
- (4) 替换当前页面:
- (5) 其他属性和方法:
- 1.4history 对象
- (1) 历史记录长度:
- (2) 向前和向后导航:
- (3)操作浏览历史:
- (4)监听历史记录变化:
- 2.DOM(文档对象模型)
- 2.1创建节点
- 2.2获取节点
- 2.3更新节点
- 2.4添加节点
- 2.5删除节点
- 2.6替换节点
- 2.7克隆节点
- 2.8attributes和data-set的区别
- 2.9Nodelist和HtmlCollection
1.BOM(浏览器对象模型)
BOM(浏览器对象模型)是指浏览器提供的一组与浏览器窗口交互的对象。BOM 不是由 W3C 标准定义的,而是由不同的浏览器厂商实现。
1.1window对象
window 对象是JavaScript 中的全局对象,代表浏览器的窗口或标签页。它是 BOM(浏览器对象模型)的核心对象,提供了与浏览器窗口交互的各种方法和属性。下面详细说明 window 对象的一些重要方面,并提供示例:
(1)全局作用域:
window 对象是 JavaScript 的全局作用域的顶层对象。在全局作用域中声明的变量和函数都会成为 window 对象的属性和方法。
let globalVariable = 'I am in the global scope';function globalFunction() {console.log('I am a global function');
}
console.log(window.globalVariable); // 访问全局变量
window.globalFunction(); // 调用全局函数
(2)窗口属性:
window 对象提供了许多与浏览器窗口相关的属性,例如窗口的大小、位置和滚动位置等。
// 获取窗口大小
console.log('Window Width:', window.innerWidth);
console.log('Window Height:', window.innerHeight);// 获取滚动位置
console.log('Scroll Top:', window.scrollY);
console.log('Scroll Left:', window.scrollX);
(3)弹窗和对话框:
window 对象提供了弹窗和对话框的方法,例如 alert、confirm 和 prompt。
// 弹出警告框
window.alert('Hello, window!');// 弹出确认框
const userConfirmed = window.confirm('Are you sure?');
console.log('User Confirmed:', userConfirmed);// 弹出提示框
const userInput = window.prompt('Enter something:');
console.log('User Input:', userInput);
(4)定时器:
window 对象可以用来设置定时器,执行一些操作或代码块。
// 设置定时器
const timeoutId = window.setTimeout(function() {console.log('Timeout completed');
}, 2000);// 清除定时器
window.clearTimeout(timeoutId);
(5)导航和历史:
window 对象提供了与浏览器导航和历史相关的方法,例如 window.location 和 window.history。
// 导航到新 URL
window.location.href = 'https://www.example.com';// 后退一页
window.history.back();
(6)打开和关闭窗口:
window 对象可以用于打开和关闭新的浏览器窗口或标签页。
// 打开新窗口
const newWindow = window.open('https://www.example.com', '_blank');// 关闭窗口
newWindow.close();
1.2navigator对象
navigator 对象是 JavaScript 中的 BOM(浏览器对象模型)对象之一,它提供了有关浏览器的信息。下面详细说明 navigator 对象的一些属性和方法,并提供相应的示例:
(1)浏览器信息属性:
navigator
对象包含了一些属性,用于获取关于浏览器的基本信息。
navigator.userAgent
: 返回包含用户代理字符串的字符串。
const userAgentString = navigator.userAgent;
console.log('User Agent:', userAgentString);
navigator.appName
: 返回浏览器的名称(已废弃)。
const browserName = navigator.appName;
console.log('Browser Name:', browserName);
navigator.appVersion
: 返回包含浏览器版本信息的字符串。
const browserVersion = navigator.appVersion;
console.log('Browser Version:', browserVersion);
(2)浏览器功能检测:
navigator对象还提供了一些方法,用于检测浏览器的特定功能。
navigator.cookieEnabled
: 返回一个布尔值,表示浏览器是否启用了 cookie。
const areCookiesEnabled = navigator.cookieEnabled;
console.log('Cookies Enabled:', areCookiesEnabled);
- 其他功能检测方法,如
navigator.geolocation
、navigator.onLine
等。
// 检测是否支持地理位置信息
if (navigator.geolocation) {console.log('Geolocation is supported');
} else {console.log('Geolocation is not supported');
}
(3)媒体功能检测:
navigator对象提供了一些方法,用于检测浏览器的媒体功能。
navigator.mediaDevices.getUserMedia()
: 检测用户是否允许访问媒体设备(摄像头、麦克风等)。
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {console.log('Media access granted');}).catch(error => {console.error('Media access denied:', error);});
(4)其他属性和方法:
navigator 对象还包含其他一些属性和方法,用于检测浏览器的支持和功能。
navigator.language
: 返回浏览器当前使用的语言。
const userLanguage = navigator.language;
console.log('User Language:', userLanguage);
navigator.plugins
: 返回一个插件数组,表示浏览器安装的插件。
const installedPlugins = navigator.plugins;
console.log('Installed Plugins:', installedPlugins);
一个常见应用:用navigator对象检测当前浏览器是否有某些插件,没有插件需要提示安装,如下:
function hasPlugins(name){for (let i=0;i<navigator.plugins.length;i++){if (navigator.plugins[i].name.toLowerCase()===name.toLowerCase()){return true}}return false;
}
1.3location 对象
location 对象是 JavaScript 中的 BOM(浏览器对象模型)对象之一,代表当前窗口的 URL 信息。它提供了访问和操作浏览器地址栏的接口。下面详细说明 location 对象的一些属性和方法,并提供相应的示例:
(1)获取和设置 URL 信息:
location 对象的属性用于获取和设置与当前 URL 相关的信息。
location.href
: 获取或设置完整的 URL。
const currentURL = location.href;
console.log('Current URL:', currentURL);
location.protocol
: 获取 URL 的协议部分(通常是 “http:” 或 “https:”)。
const protocol = location.protocol;
console.log('Protocol:', protocol);
location.host
: 获取 URL 的主机部分(包括端口号)。
const host = location.host;
console.log('Host:', host);
location.pathname
: 获取 URL 的路径部分。
const path = location.pathname;
console.log('Path:', path);
location.search
: 获取 URL 的查询字符串部分。
const queryString = location.search;
console.log('Query String:', queryString);
(2)页面导航:
location 对象的方法用于在页面之间进行导航。
location.assign(url)
: 加载新的文档。
// 导航到新的页面
location.assign('https://www.example.com');
location.reload()
: 重新加载当前文档。
// 重新加载页面
location.reload();
(3)操作浏览历史:
location 对象与浏览器的历史记录有关。
location.back()
: 在浏览器历史记录中后退一步。
// 后退一步
location.back();
location.forward()
: 在浏览器历史记录中前进一步。
// 前进一步
location.forward();
(4) 替换当前页面:
location 对象的方法可以用新的 URL 替换当前页面。
location.replace(url)
: 用新的文档替换当前文档,不会在历史记录中留下记录。
// 替换当前页面
location.replace('https://www.example.com');
ps:location.href
和location.replace
的区别?
location.href="xxx"
------>修改地址,存入到栈中;
location.replace("xxx")
------>修改地址,不会存入到栈中,不会在历史记录中留下记录;
(5) 其他属性和方法:
location 对象还包含其他一些属性和方法,用于操作当前页面的 URL。
location.hash
: 获取或设置 URL 的片段标识符(# 后面的部分)。
const fragmentIdentifier = location.hash;
console.log('Fragment Identifier:', fragmentIdentifier);
location.searchParams
: 获取 URL 查询参数的对象。
const queryParams = location.searchParams;
console.log('Query Params:', queryParams);
1.4history 对象
history 对象是 JavaScript 中的 BOM(浏览器对象模型)对象之一,代表浏览器的浏览历史记录。它提供了一些方法,允许 JavaScript 在用户浏览历史记录中向前和向后导航。下面详细说明 history 对象的一些属性和方法,并提供相应的示例:
(1) 历史记录长度:
history 对象的属性用于获取浏览器历史记录中的条目数量。
history.length
: 返回历史记录中的条目数量。
const historyLength = history.length;
console.log('History Length:', historyLength);
(2) 向前和向后导航:
history 对象的方法允许在用户的浏览历史记录中进行导航。
history.back()
: 在浏览器历史记录中后退一步。
// 后退一步
history.back();
history.forward()
: 在浏览器历史记录中前进一步。
// 前进一步
history.forward();
history.go(delta)
: 在浏览器历史记录中相对于当前页面进行导航,delta 参数表示相对当前页面的步数,可以为正数(向前)或负数(向后)。
// 向前导航两步
history.go(2);// 向后导航一步
history.go(-1);
(3)操作浏览历史:
history 对象的方法允许在浏览器历史记录中添加、替换和删除条目。
history.pushState(state, title, url)
: 向浏览历史记录添加新的条目。
const newState = { page: 'home' };
const newTitle = 'Home Page';
const newURL = '/home';
history.pushState(newState, newTitle, newURL);
history.replaceState(state, title, url)
: 用新的状态替换当前浏览历史记录中的条目。
const updatedState = { page: 'about' };
const updatedTitle = 'About Page';
const updatedURL = '/about';
history.replaceState(updatedState, updatedTitle, updatedURL);
(4)监听历史记录变化:
history 对象允许通过事件监听历史记录的变化。
popstate 事件
:在浏览历史记录发生变化时触发。
window.addEventListener('popstate', event => {console.log('History state changed:', event.state);
});
2.DOM(文档对象模型)
在 JavaScript 中,DOM(文档对象模型)是表示和操作 HTML 或 XML 文档的标准接口。DOM 提供了一种在代码中动态访问和更新文档的方式。文档节点是 DOM 中的最顶层节点,代表整个文档。下面详细说明文档节点的一些概念和操作,并提供相应的示例。
2.1创建节点
- 创建一个指定标签名的元素节点:
document.createElement(tagName)
; - 创建一个包含指定文本内容的文本节点:
document.createTextNode(text)
; - 创建文档碎片(可以减少回流)
// 创建一个空的DOM文档碎片
let fragment = document.createDocumentFragment();
// 创建一些元素
let p1 = document.createElement('p');
p1.textContent = 'This is a paragraph.';
let p2 = document.createElement('p');
p2.textContent = 'This is another paragraph.';
// 将元素添加到文档碎片中
fragment.appendChild(p1);
fragment.appendChild(p2);
// 最后,将文档碎片添加到页面上
document.body.appendChild(fragment);
2.2获取节点
getElementById
:获取文档中指定 ID的元素getElementsByClassName
:获取文档中指定类名的所有元素getElementsByTagName
:通过标签名获取元素querySelector
通过CSS选择器获取第一个匹配的元素querySelectorAll
通过CSS选择器获取所有匹配的元素,返回NodeListparentNode
、childNodes
、firstChild
、lastChild
、nextSibling
、previousSibling
…
// 获取指定元素的下一个兄弟节点(可能是元素、文本或其他类型)
var nextSibling = element.nextSibling;// 获取指定元素的上一个兄弟节点(可能是元素、文本或其他类型)
var prevSibling = element.previousSibling;
2.3更新节点
innerHtml
:获取或设置从对象的起始位置到终止位置的全部内容,包括 Html 标签
document.getElementById('myDiv').innerHTML = '<h1>Hello, World!</h1>';
innerText
:textContent
:
<div id="myDiv"><span style="display: none;">隐藏的文本</span>可见文本
</div>
<script>const myDiv = document.getElementById('myDiv');console.log(myDiv.textContent); // 输出:"\n 隐藏的文本\n 可见文本\n"console.log(myDiv.innerText); // 输出:"可见文本"
</script>
innerText
和textContent
的区别可见文章https://blog.csdn.net/weixin_45342302/article/details/135589320
- 修改节点css样式:style,className,classList
- 修改节点的html属性:已有的属性可以直接打点;没有的属性通过setAttribute的操作:
element.setAttribute("data-n",10);
2.4添加节点
appendChild
;
let parent = document.getElementById("parent");
let child = document.getElementById("child");
parent.appendChild(child);
insertBefore(newEl,el)
;插在el元素之前
targetElement.parentNode.insertBefore(newElement, targetElement);
2.5删除节点
removeChild(元素)
parent.removeChild(child)
2.6替换节点
replaceChild(newNode,oldNode)
let oldnode = document.getElementById("oldElementId");
let newnode = document.createElement("div");
newnode.innerHTML = "新内容";
oldnode.parentNode.replaceChild(newnode, oldnode);
2.7克隆节点
cloneNode
// 获取要克隆的节点
var originalNode = document.getElementById("original");
// 克隆节点,深拷贝
var clonedNode = originalNode.cloneNode(true);
// 将克隆的节点插入到文档中
document.body.appendChild(clonedNode);
2.8attributes和data-set的区别
我们来看一个例子(下面这个了解一下即可):
<div class="box" id="test" value="value" title="123" data-name="box" data-time="12" title1="qqq"></div><script>let box=document.querySelector(".box");console.log(box.attributes)//包含:class,id,value,title,data-name,data-time,title1console.log(box.dataset.name)//"box"console.log(box.attributes['data-time'].name)//"data-time"console.log(box.attributes['data-time'].value)//12console.log(box.getAttribute("data-name"))//boxconsole.log(box.getAttribute("title1"))//qqqconsole.log(box.title1)//undefined property只能得到dom的非自定义的属性box.title="test"console.log(box.getAttribute("title"))//testbox.value="123"console.log(box.getAttribute("value"))valuebox.test1="222"console.log(box.getAttribute("test1"))//nullbox.setAttribute("test2", "test2---");console.log(box.getAttribute("test2")); //test2---</script>
2.9Nodelist和HtmlCollection
document.querySelector("xxx")
和document.querySelectorAll
的结果就是Nodelist
类型。
<div class="list"><div class="list-item">1</div><div class="list-item">2</div><div class="list-item">3</div><div class="list-item">3</div></div><button>复制</button><script>console.log(document.querySelectorAll(".list-item"));</script>
控制台打印如下:
之前浏览器中旧的查询节点的Api(如getElementsByClassName
)返回的结果是就htmlCollection
(如下):
<div class="list"><div class="list-item">1</div><div class="list-item">2</div><div class="list-item">3</div><div class="list-item">3</div></div><button>复制</button><script>console.log(document.getElementsByClassName("list-item"));</script>
控制台打印如下:
注意:
Nodelist
和HtmlCollection
不是数组,是类数组对象。- 网页上节点变化,htmlCollection集合会立马发生变化
下面来看一个实例:
<div class="list"><div class="list-item">1</div><div class="list-item">2</div><div class="list-item">3</div><div class="list-item">3</div></div><button>复制</button><script>let list=document.querySelector(".list")let button=document.querySelector("button")button.addEventListener("click",function(){let listItems=document.querySelectorAll(".list-item");//不能用下面这行代码、它会导致死循环,下面的listItems会随着页面的变化随时变化// let listItems=document.getElementsByClassName("list-item");for (let i=0;i<listItems.length;i++){console.log(i)let cloneDom=listItems[i].cloneNode(true);list.appendChild(cloneDom)}})</script>
这个代码刚好印证了网页上节点变化,htmlCollection
集合会立马发生变化。