当前位置: 首页 > Web前端 > JavaScript

JavaScript——DOM和BOM

时间:2023-03-27 01:07:41 JavaScript

DOM加载网页时,浏览器会创建页面的文档对象模型(DOM)。通过DOM,JavaScript可以访问和更改页面元素。BOM通过浏览器对象模型(BOM),JavaScript可以与浏览器对话。1.通过id查找元素,没有找到则返回nullvare=document.getElementById("intro");按标签名搜索,返回一个集合(如果没有找到,集合为空)varps=document.getElementsByTagName("p");按类名搜索,返回一个集合(没有找到则集合为空)varintros=document.getElementsByClassName("intro");通过选择器查找//找到第一个满足条件的元素,没有找到返回nullvarx=document.querySelector("p.intro");//找到所有满足条件的元素,返回一个列表(如果没有找到发现,列表是空的)varxs=document.querySelectorAll("p.intro");上面的例子是在文档中查找元素,所以指定为文档,也可以在指定的父元素中查找:varx=document.getElementById("main");vary=x.getElementsByTagName(“p”);2.操作元素元素内容varp1=document.querySelector("#p1");console.log(p1.innerText);//文本内容console.log(p1.innerHTML);//html内容p1.innerHTML="Hello,DOM!"元素属性varimg=document.querySelector("#image");console.log(img.src);img.src="/i/保时捷.jpg";CSS样式直接修改style属性:document.getElementById('id1').style.color='red';通过修改元素的类名来改变CSS样式:document.getElementById('id1').className='btn';.btn{color:blue;}3.鼠标点击事件等事件处理器:document.getElementById("myBtn").onclick=displayDate;或者:点击这个文本!你也可以通过注册事件监听器来处理事件:document.getElementById("myBtn").addEventListener("点击",myFunction);functionmyFunction(){alert("HelloWorld!");}事件传播DOM中有两种事件传播方法,addEventListener()的第三个参数用于表示冒泡(false):最内层元素的事件将首先处理,然后是外部的;capture(true):先处理最外层元素的事件,再处理最里面的document.getElementById("myP").addEventListener("click",myFunction,true);删除事件处理程序document.getElementById("myDIV").onmousemove=myFunction;//或document.getElementById("myDIV").addEventListener("mousemove",myFunction);document.getElementById("myDIV").removeEventListener("mousemove",我的函数);4、一次性定时器t1=setTimeout(f,ms):ms毫秒后执行函数f。clearTimeout(t1):在定时器t1到期之前停止它。Intervalt2=setInterval(f,ms):每ms毫秒执行一次函数f。clearInterval(t2):停止定时器t2。vart=setInterval(myTimer,1000);functionmyTimer(){vard=newDate();document.getElementById("demo").innerHTML=d.toLocaleTimeString();停止时间5.locationslocation.href:用于获取或修改当前页面的URL。varurl=location.href;location.href="https://www.baidu.com";//会保留浏览历史location.replace():替换当前页面,不会保留上次浏览记录(已删除replace)。location.replace("https://fanyi.sogou.com/")location.reload():重新加载页面。位置.reload();location.reload(true);//不使用之前的缓存6.historyhistory.back():加载历史列表中的之前的URL。historyforward():加载历史列表中的下一个URL。