【一】什么是BOM/DOM
- BOM,浏览器对象模型,它使得JavaScript有能力与浏览器进行对话
- DOM,文档对象模型,可以通过它访问HTML文档的所有元素
- 他们是JavaScript与浏览器以及网页内容进行交互的核心
【1】BOM#
- 浏览器对象模型(BOM)则是浏览器提供的API集合,主要用于处理与浏览器环境相关的任务,如窗口管理、导航、cookie、location等。
-- 打开新的浏览器窗口
window.open('https://www.baidu.com','','height=400px,width=400px')
-- 获取当前页面的URL地址
window.location.href
-- 返回历史记录中的上一页
window.history.back()
-- 获取浏览器信息
navigator.userAgent
【2】DOM#
- 文档对象模型(DOM)是一个编程接口,它以树状结构来表示 HTML 或 XML 文档。
- 在 DOM 中,每个HTML元素、属性、文本节点等都被视为一个对象,通过JavaScript可以创建、查询、修改和删除这些对象。
-- 通过元素ID获得DOM元素对象
document.getElementById('d1')
-- 根据CSS选择器或伪类选择DOM元素对象。
element.querySelector/pseudo-class
-- 向指定元素添加子元素。
element.appendChild(newElement)
-- 设置元素属性值。
element.setAttribute(name, value)
-- 获取或设置元素内的文本内容或HTML内容
element.innerText/innerHTML
【3】总结#
- DOM 和 BOM 是 JavaScript 开发中两个不可或缺的部分,分别负责对网页内容和浏览器环境进行深层次的操作,使得前端开发者能够实现丰富的交互功能和动态效果。
【二】Window对象
- Window对象是JavaScript中表示浏览器窗口的全局对象,它提供了一系列方法来操作和管理窗口。
【1】open()#
- 打开新窗口或者获取对一个已经存在的窗口的引用。
- 第一个参数是目标网址,第二个参数可以为空,第三个参数为窗口的大小
window.open('https://www.baidu.com','','width=400px,height=400px')
【2】close()#
【3】setTimeout()#
setTimeout(function index() {
console.log('hello word')
},300)
【4】setInterval()#
setInterval(function(){
console.log('hello word')
},3000)
【5】alert()#
window.alert('你不要过来啊')
【6】confirm()#
- 显示一个带有指定消息和两个按钮(确认和取消)的对话框。
- 点击确认返回true
- 点击取消返回false
window.confirm('你好吗')
【7】prompt()#
- 显示一个带有指定消息和一个文本输入框的对话框。
- 点击确认后会返回输入框里面的内容
window.prompt('你叫什么名字')
【8】innerHeight属性#
- 返回浏览器窗口的内部高度(即视口的高度),以像素为单位,不包括浏览器的工具栏、滚动条等元素。
window.innerHeight
906
【9】innerWidth属性#
- 返回浏览器窗口的内部宽度(即视口的宽度),以像素为单位,不包括浏览器的工具栏、滚动条等元素。
window.innerWidth
1707
【三】Window子对象
【1】window.document#
- 此子对象表示当前窗口中的文档对象,用于对页面内容进行读取和修改操作。
- 通过
window.document
,可以使用各种方法来查询和修改当前页面的 HTML 结构、CSS 样式和 DOM 元素。
var divEle = document.getElementById('d1')
【2】window.location#
- 此子对象包含有关当前页面 URL 的信息,并提供了一些与页面导航相关的方法。
- 通过
window.location
,可以获取当前页面的 URL、查询字符串参数、路径等信息,并且可以使用一些方法来导航到其他页面。
window.location
Location {ancestorOrigins: DOMStringList, href: 'http://localhost:63342/python28/%E5%89%8D%E7%AB%AF…258j31kgcq6oe8abplj7uvs&_ij_reload=RELOAD_ON_SAVE', origin: 'http://localhost:63342', protocol: 'http:', host: 'localhost:63342', …}
window.location.href*
window.location.protocol
window.location.host
window.location.hostname
window.location.port
window.location.pathname
window.location.search
window.location.hash
window.location.assign("http://example.com");
window.location.reload()*
【3】window.history#
- 此子对象用于操作浏览器的历史记录,包括向前和向后导航
window.history.length
window.history.back()*
window.history.forward()*
window.history.go()
window.history.pushState({ page: 1 }, "Page 1", "/page1.html");
window.history.replaceState({ page: 2 }, "Page 2", "/page2.html");
【4】window.navigator#
- 此子对象用于提供有关浏览器环境和设备的信息,包括用户代理字符串、浏览器版本、操作系统等。
window.navigator.userAgent*
window.navigator.platform*
window.navigator.vendor;
window.navigator.language;
window.navigator.cookieEnabled;
window.navigator.plugins;
【四】弹出框
- 弹出框是网页开发中常用的交互组件,用于显示警告、确认或提示信息,并与用户进行互动。
- 常见的弹出框类型包括警告框、确认框和提示框。
alert("这是一个警告框!");
confirm("你确定要删除吗?")
prompt("请输入您的姓名:", "默认值");
【五】计时器
- 计时器在网页开发中经常用于实现定时触发某些操作的功能。
- 根据需求,可以使用不同的方法来触发定时器。
【1】过一段时间触发(setTimeout)#
- 如果需要在经过一定的时间后触发某个操作
- 就可以使用setTimeout函数来设置定时器
- 时间参数的单位为毫秒
setTimeout(function index() {
console.log('hello word')
},3000)
【2】每隔一段时间触发一次(setInterval)#
- 如果需要每隔一段时间就执行一段代码
- 就可以使用setInterval函数来设置定时器
setInterval(function index() {
console.log('hello word')
},3000)
【3】清除定时器(clearTimeout/clearInterval)#
var timer = setTimeout(function() {
}, 5000);
clearTimeout(timer);
-------------------------------------------
var timer = setInterval(function() {
}, 2000);
clearInterval(timer);
【六】查找标签
- 直接查找标签和间接查找标签是在Web开发中常用的两种方式。
- 操作页面的时候需要用到document对象
【1】直接查找标签#
var divEle = document.getElementById('d1')
document.getElementsByTagName('div')
document.getElementsByClassName('d3')
【2】间接查找标签#
parentElement
parentElement
children
firstElementChild
lastElementChild
nextElementSibling
previousElementSibling
【七】节点操作
- 节点操作是指文档对象模型DOM对节点进行创建,获取,修改,删除等操作
【1】创建节点#
document.createElement('img')
document.createTextNode('你好啊')
createDocumentFragment()
【2】获取节点#
getElementById(id)
getElementsByTagName(tagName)
getElementsByClassName(className)
querySelector(selector)
querySelectorAll(selector)
【3】修改节点#
node.appendChild(childNode)
parent.removeChild(childNode)
node.replaceChild(newNode, oldNode)
node.insertBefore(newNode, referenceNode)
【4】属性操作#
element.getAttribute(attribute)
element.setAttribute(attribute, value)
element.removeAttribute(attribute)
【5】文本操作#
node.textContent
node.innerHTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="d1">div1
<p>p1</p>
<span id="s1">span1</span>
</div>
</body>
</html>
let imgEle = document.createElement('img')
let divEle = document.getElementById('d1')
imgEle.src='111.png'
divEle.appendChild(imgEle)
imgEle.setAttribute('name','green')
imgEle.setAttribute('title','妹子')
<script>
let divEle = document.getElementById('d1')
let aEle = document.createElement('a')
let pEle = document.getElementById('p1')
aEle.setAttribute('href', 'https://www.baidu.com')
aEle.innerText='跳转百度'
divEle.insertBefore(aEle,pEle)
</script>
【八】获取值操作
【1】获取属性值#
- 可以使用
getAttribute()
方法来获取HTML元素的属性值。
- 该方法需要传入属性名作为参数,并返回属性对应的值。
let srcValue = aEle.getAttribute('href')
【2】获取文本内容#
- 可以使用
innerText
、innerHTML
或textContent
属性来获取一个元素的文本内容。
- 这些属性会返回元素内包含的文本,但存在一些差异:
innerText
:返回元素的纯文本内容,不包括HTML标记。
innerHTML
:返回元素的HTML内容,包括HTML标记。
textContent
:返回元素及其所有子元素的文本内容,包括隐藏元素和注释等。
divEle.innerHTML
'div1\n <p>p1</p>\n <span id="s1">span1</span>\n<a href="https://www.baidu.com">跳转百度</a>'
divEle.innerText
'div1\n\np1\n\nspan1 跳转百度'
divEle.textContent
'div1\n p1\n span1\n跳转百度'
【3】获取用户输入值#
- 对于表单元素(如input、select、textarea等)
- 可以通过获取其
value
属性来获取用户输入的值。
inputEle.value
【4】获取文件#
- 当用户选择了一个或者多个文件之后
- 通过files属性可以获取这些文件的信息
- files属性返回一个filelist对象
fileEle.files
【九】属性操作
【1】class属性操作#
- .classList() 是JavaScript中用于获取HTML元素的类名列表的方法。
- 它返回一个DOMTokenList对象,该对象包含了元素的所有类名。
使用示例#
let divEle = document.getElementById('d4')
divEle.classList
classList.add("newClass");
classList.remove("oldClass");
classList.toggle("active");
注意事项#
classList
是只读的,不能直接赋值。
classList
是一个动态的列表,会实时反映元素的当前类名状态。
- 可以通过遍历
classList
来访问每个类名,或者使用length
属性获取类名数量。
classList
方法在大多数现代浏览器中都得到了支持。
- 如果需要兼容旧版浏览器,可以考虑使用polyfill库来模拟
classList
功能。
【案例】标签样式#
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d4 {
width: 300px;
height: 300px;
border-radius: 50%;
}
.bg_red {
background-color: red;
}
.bg_green {
background-color: greenyellow;
}
</style>
</head>
<body>
<div id="d1">div1
<p id="p1">p1</p>
<div id="d4" class="c1 bg_green bg_red"></div>
</div>
<script>
</script>
</body>
</html>
类属性操作#
let divEle = document.getElementById("d4");
divEle.classList
divEle.remove('bg_green)
// 添加某个类
divEle.remove('bg_green)
divEle.classList.contains("d1")
divEle.classList.toggle("bg_red");
标签样式操作#
let pEle = document.getElementById('p1')
pEle.style.color = 'red'
pEle.style.fontSize = '48px'
pEle.style.backgroundColor = 'pink'
【十】事件
- 事件是指程序执行期间发生的特定操作或者状态变化
- 事件可以来自用户的交互操作(如鼠标点击,鼠标移动等),也可以是其他元素或系统发出的通知(如定时器到期、网络请求完成等)。
- 事件触发后,程序可以执行相应的处理函数来响应事件并做出相应的操作。
【1】鼠标事件#
- click:鼠标点击事件。
- mouseover:鼠标悬停在元素上的事件。
- mouseout:鼠标离开元素的事件。
- mousedown:鼠标按下事件。
- mouseup:鼠标松开事件。
- mousemove:鼠标移动事件。
【2】键盘事件#
- keydown:键盘按下事件。
- keyup:键盘松开事件。
- keypress:键盘按键被按下并松开事件。
【3】表单事件:#
- submit:表单提交事件。
- change:表单值改变事件。
- focus:表单元素获取焦点事件。
- blur:表单元素失去焦点事件。
【4】文档加载事件:#
- load:页面完全加载完成事件。
- unload:页面关闭或离开事件。
【5】定时器事件#
- setTimeout:在指定的延迟时间后触发事件。
- setInterval:每隔一定时间触发事件。
【6】自定义事件:#
- 开发者可以根据需要创建自定义事件,并使用dispatchEvent来触发事件。
【十一】绑定事件的两种方式
【1】传统的事件属性绑定#
- 通过在HTML标签内直接添加事件属性来实现事件的绑定
<button onclick='index()'>点我</button>
<script>
function index(){
alert('你好')
}
</script>
【2】现代的事件监听绑定#
- 通过JavaScript代码动态的选择元素,并以代码方式绑定事件监听器
- HTML和JavaScript代码会分离,提高了代码的可读性和可维护性。
let btnEle = document.getElementById('d5')
btnEle.addEventListener('click',function (){
alert('你好')
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d4 {
width: 300px;
height: 300px;
border-radius: 50%;
}
.bg_red {
background-color: red;
}
.bg_green {
background-color: greenyellow;
}
</style>
</head>
<body>
<div id="d1">div1
<p id="p1">p1</p>
<span id="s1">span1</span>
<input type="text" id="d2" value="你好啊">
<input type="file" id="d3">
<div id="d4" class="c1 bg_green bg_red"></div>
<button id="d5">开关</button>
</div>
<script>
</script>
</body>
</html>
let btnEle = document.getElementById('d5')
let divEle = document.getElementById('d4')
btnEle.onclick = function (){
divEle.classList.toggle('bg_green')
}
btnEle.addEventListener('click',function (){
divEle.classList.toggle('bg_green')
})
let inputEle = document.getElementById('d2')
inputEle.onblur = function (){
inputEle.value = '你好啊'
}
inputEle.onfocus = function (){
inputEle.value = ''
}
// 动态展示时间案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
</head>
<body>
<div id="d1">div1
<input type="text" id="d2" style="display: block;width: 300px;height: 40px" >
<button id="d3">开始</button><button id="d4">结束</button>
</div>
<script>
let t = null
let inputEle = document.getElementById('d2')
let startBtnEle = document.getElementById('d3')
let endBtnEle = document.getElementById('d4')
function showTime(){
let timeObj = new Date()
inputEle.value = timeObj.toLocaleString()
}
startBtnEle.onclick = function (){
if (!t){
t = setInterval(showTime,1000)
}
}
endBtnEle.onclick = function (){
clearInterval(t)
t = null
}
</script>
</body>
</html>
// 省市联动单例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<select id="s1">
<option value="请选择" disabled="disabled" selected="selected">--请选择--</option>
</select>
<select id="s2"></select>
<script>
let data = {
'浙江': ['杭州市', '台州市', '嘉兴市'],
'上海': ['浦东区', '黄浦区', '静安区'],
'北京': ['朝阳区', '昌平区', '海淀区']
}
let proEle = document.getElementById('s1')
let cityEle = document.getElementById('s2')
for (i in data) {
let opEle = document.createElement('option')
opEle.value = i
opEle.innerText = i
proEle.appendChild(opEle)
}
proEle.onchange = function () {
cityEle.innerHTML = ''
let opEle = document.createElement('option')
opEle.innerText = '--请选择--'
opEle.setAttribute('selected','selected')
opEle.setAttribute('disabled','disabled')
cityEle.appendChild(opEle)
let currentPro = proEle.value
let currentCityList = data[currentPro]
console.log(currentCityList)
for (let i = 0; i < currentCityList.length; i++) {
let opEle = document.createElement('option')
opEle.value = currentCityList[i]
opEle.innerText = currentCityList[i]
cityEle.appendChild(opEle)
}
}
</script>
</body>
</html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!