JavaScript window 、Document 、Location、History、Navigator,页面刷新方式汇总

本文深入讲解JavaScript中的核心对象,如window、Document、Location等,涵盖了对象的属性、方法及使用技巧,帮助读者全面掌握JavaScript编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

window 窗口对象

Document 文档对象

改变 HTML 元素与属性

获取元素展示状态,设置元素隐藏与展示

Location 对象

History 对象

页面刷新方式汇总


window 窗口对象

菜鸟教程:Window 对象 | 菜鸟教程

1、API 演示:src/main/resources/static/windowTest.html · 汪少棠/web_app - Gitee.com

2、所有浏览器都支持 window 对象。它表示浏览器窗口。

3、所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。

4、全局变量是 window 对象的属性。全局函数是 window 对象的方法。

5、甚至 HTML DOM 的 document 也是 window 对象的属性之一,window.document.getElementById("xxx");

 6、全局变量不能通过 delete 操作符删除,而 window 属性上定义的变量可以通过 delete 删除。


let num = 123;
window.str = "蚩尤后裔";
delete num;
delete str;
console.log(num); // 123
console.log(str); // str is not defined

 7、访问未声明的变量会抛出错误,但是通过查询 window 对象,可以知道某个可能未声明的变量是否存在。


let newValue1 = window.oldValue; // 不会报错
console.log(newValue1); // undefined
let newValue2 = oldValue; // 报错:oldValue is not defined

 8、有些自执行函数里面的变量,想要外部也访问到的话,在 window 对象上直接定义属性。

常用属性

描述

// 三种方法获取浏览器窗口文档显示区的尺寸(包括滚动条)

let windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

let windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

window.document.getElementById("tip1").innerText = "窗口宽:" + windowWidth + ",高:" + windowHeight;

// 获取浏览器窗口外部尺寸

let windowWidth = window.outerWidth;

let windowHeight = window.outerHeight;

window.document.getElementById("tip1").innerText = "窗口外部宽:" + windowWidth + ",高:" + windowHeight;

// screen.availWidth 属性返回访问者屏幕的宽度,以像素计,减去界面特性,比如窗口任务栏。

// screen.availHeight 属性返回访问者屏幕的高度,以像素计,减去界面特性,比如窗口任务栏。

let availWidth = window.screen.availWidth;

let availHeight = window.screen.availHeight;

window.document.getElementById("tip3").innerText = "可用宽度:" + availWidth + ",可用高度:" + availHeight;

window.document.getElementById("tip4").innerText = "屏幕总宽度,高度::" + screen.width + ", " + screen.height;

localStorage

localStorage 和 sessionStorage 属性允许在浏览器中存储 key/value 对的数据。

localStorage 用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去删除。

sessionStorage

pageXOffset

1、pageXOffset 和 pageYOffset 属性返回文档在窗口左上角水平和垂直方向滚动的像素。

2、pageXOffset 设置或返回当前页面相对于窗口显示区左上角的 X 位置。pageYOffset 设置或返回当前页面相对于窗口显示区左上角的 Y 位置。

3、pageXOffset 和 pageYOffset 属性相等于 scrollX 和 scrollY 属性。

pageYOffset

常用方法

描述

window.open()

打开新窗口.

window.close()

关闭当前窗口

window.moveTo()

移动当前窗口

window.resizeTo()

调整当前窗口的尺寸

getSelection()

表示用户选择的文本范围或光标的当前位置。

getComputedStyle()

用于获取指定元素的 CSS 样式,获取的样式是元素在浏览器中最终渲染效果的样式。

1、getComputedStyle 和 element.style 的相同点是二者返回的都是 CSSStyleDeclaration 对象,取相应属性值得时候都是采用的 CSS 驼峰式写法,均需要注意 float 属性。

2、element.style 读取的只是元素的内联样式,即写在元素的 style 属性上的样式;而 getComputedStyle 读取的是最终样式,包括了内联样式、嵌入样式和外部样式。

3、element.style 既支持读也支持写,而 getComputedStyle 仅支持读并不支持写入。可以通过使用 getComputedStyle 读取样式,通过 element.style 修改样式。

window.print()

用于打印当前窗口的内容。等同于浏览器的打印操作。

scrollBy(xnum,ynum)

相对当前位置把内容滚动指定的像素数。

1、注意 要使此方法工作,window 滚动条的可见属性必须设置为 true。

scrollTo(xpos,ypos)

把内容滚动到指定的坐标。

Document 文档对象

JavaScript HTML DOM | 菜鸟教程

1、通过 HTML DOM,可访问 JavaScript HTML 文档的所有元素。

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

3、通过可编程的对象模型,JavaScript 获得了足够的能力来创建动态的 HTML。

4、根据 W3C 的 HTML DOM 标准,HTML 文档中的所有内容都是节点:

  • 整个文档是一个文档节点
  • 每个 HTML 元素是元素节点
  • HTML 元素内的文本是文本节点,可通过节点的 innerHTML 属性来访问文本节点的值。
  • 每个 HTML 属性是属性节点
  • 注释是注释节点

属性 / 方法描述
document.activeElement返回当前获取焦点元素
document.addEventListener()向文档添加句柄
document.baseURI返回文档的绝对基础 URI
document.body [= newContent]

用于设置或返回文档体。

如果是返回, 该属性返回当前文档的 <body> 元素
如果是设置, 该属性会覆盖所有在 <body> 元素中的子元素, 并用新的内容来替换它。

document.body.style.backgroundColor = "yellow";

document.documentElement

返回整个 Html 元素, 如果 HTML 元素缺失,返回值为 null。

document.documentElement.innerHTML

document.cookie

设置或返回与当前文档有关的所有 cookie。

document.write(document.cookie);// 返回与当前文档相关的所有 cookies

document.createAttribute()

创建一个属性节点。

var att=document.createAttribute("class");
att.value="democlass";
document.getElementsByTagName("H1")[0].setAttributeNode(att);

document.createComment()createComment() 方法可创建注释节点。
document.createDocumentFragment()创建空的 DocumentFragment 对象,并返回此对象。
document.createElement()创建元素节点。
document.createTextNode()创建文本节点。
document.domain

返回下载当前文档的服务器域名或者IP。

console.log(document.domain);//返回加载的文档的服务器域名

document.forms[].property返回对文档中所有 Form 对象引用。
document.forms.length; // 返回文档中表单的数目
document.forms[0].name;// 返回文档中第一个表单的 name 属性值
 document.getElementsByClassName(classname)返回文档中所有指定类名的元素集合,作为 NodeList 对象。
document.getElementById(elementID)

返回对拥有指定 id 的第一个对象的引用。

如果没有指定 ID 的元素返回 null。

如果存在多个指定 ID 的元素则返回第一个。

 document.getElementsByName(name)返回带有指定名称的对象集合。
 document.getElementsByTagName(tagname)

返回带有指定标签名的对象集合。参数值 "*" 返回文档的所有元素。

未找到时返回空集合。

document.images[].property

返回对文档中所有 Image 对象引用。

document.images.length; // 返回文档中的图像数
document.images[0].id; // 返回文档中第一个图像的ID属性值

document.lastModified返回文档被最后修改的日期和时间。
document.querySelector(CSS selectors)

返回文档中匹配指定的CSS选择器的第一个元素(CSS 选择器教程)。没有找到时返回 null。

CSS 选择器可以指定一个或多个(逗号隔开),可以使用 id, class, type, 属性, 属性值等来选取元素。

document.querySelectorAll(selectors)

//selectors 是一个由逗号连接的包含一个或多个 CSS 选择器的字符串。

返回文档中匹配指定 CSS 选择器的所有元素,返回 NodeList 对象。可以通过索引访问,索引值从 0 开始。没有查询到时 length 属性为0.

document.referrer

referrer 属性返回载入当前文档的来源文档的URL。

如果当前文档不是通过超级链接访问的,则为 null。

document.title

返回当前文档的标题( HTML title 元素中的文本)。

console.log(document.title);// 返回文档的标题

document.URL

返回文档完整的URL。

一般情况下,url 属性的值与 location.href 属性值相同。不过在URL重定向时,URL属性保存了文档的实际URL,而 location.href 保存了请求的URL。

write(exp1,exp2,exp3,...)

向文档写 HTML 表达式 或 JavaScript 代码。

如果在文档已完成加载后执行 document.write(),整个 HTML 页面将被覆盖。

document.write("<h1>Hello World!</h1>");

document.writeln()等同于 write() 方法,不同的是在每个表达式之后写一个换行符。

https://gitee.com/wangmx1993/web_app/blob/master/src/main/resources/static/DocumentTest.html

5、getElementsByTagName 和 getElementsByClassName 方法查找多个 dom 元素,返回的是 htmlcollection 类型,是伪数组而不是真数组,故不能使用数组的方法。可以使用数组原型配合 slice 方法,利用 call,apply,bind 方法将伪数组转为真数组。

let pTags = document.getElementsByTagName("p");
// 伪数组转为真数组方法1
console.log(Array.prototype.slice.call(pTags));
// 伪数组转为真数组方法2
console.log(Array.prototype.slice.apply(pTags));
// 伪数组转为真数组方法3
console.log(Array.prototype.slice.bind(pTags)());

改变 HTML 元素与属性

1、修改 HTML = 改变元素、属性、样式和事件。

改变 HTML 样式

// 格式:document.getElementById(id).style.property=新样式

// 隐藏:xx.style.visibility='hidden'
// 显示:xx.style.visibility='visible'

let pTags = document.getElementsByTagName("p");
pTags[1].style.color = "red";
pTags[1].style.fontFamily = "Arial";
pTags[1].style.fontSize = "larger";

事件触发改变

<p id="author">蚩尤后裔</p>

<button type="button" οnclick="document.getElementById('author').style.color='red'">点我</button>

创建新的 HTML 元素 (节点)

createElement()-创建元素节点。

createTextNode()-创建文本节点。

appendChild()-把新的子节点添加到指定节点。

insertBefore()-在指定的子节点前面插入新的子节点。

// 创建新的 HTML 元素 (节点) - appendChild(),然后在已存在元素的尾部添加它。
let newTag = document.createElement("p");
// 为 <p> 元素创建一个新的文本节点
let node = document.createTextNode("新元素的内容。");
// 将文本节点添加到 <p> 元素中
newTag.appendChild(node);
// 在一个已存在元素的尾部添加 p 元素
let parentTag = document.getElementsByTagName("body")[0];
parentTag.appendChild(newTag);
let newTag = document.createElement("p");
let node = document.createTextNode("新元素的内容。");
newTag.appendChild(node);
// 将新元素添加到开始位置,可以使用 insertBefore() 方法
let parentTag = document.getElementsByTagName("body")[0];
let afterTag = document.getElementById("divSubmit");
parentTag.insertBefore(newTag, afterTag);
移除已存在元素// 方式1:查找父元素并删除子元素
let parent = document.getElementById("divSubmit");
let child1 = document.getElementById("butSubmit");
parent.removeChild(child1);
// 方式2:查找子元素,然后查找其父元素,再删除这个子元素
let child2 = document.getElementById("divSubmit");
child2.parentNode.removeChild(child2);
替换 HTML 元素let newTag = document.createElement("p");
let node = document.createTextNode("新元素的内容。");
newTag.appendChild(node);
// 将新元素添加到开始位置,可以使用 insertBefore() 方法
let parentTag = document.getElementsByTagName("body")[0];
let childTag = document.getElementById("divSubmit");
parentTag.replaceChild(newTag, childTag);
操作 HTML DOM 属性
innerHTML 获取元素内容(包括html标签)

let innerHTML = document.getElementsByTagName("head")[0].innerHTML;
console.log(innerHTML);

// innerHTML 属性可用于获取或改变任意 HTML 元素,包括 <html> 和 <body>

innerText 获取元素文本内容(不包括html标签)let element = document.getElementById("divSubmit");
console.log(element.innerText);
innerHTML 设置元素内容(包括html标签)

document.getElementById(id).innerHTML=新HTML

// 修改 HTML 内容的最简单的方法是使用 innerHTML 属性。

value 属性获取表单值

姓名:<input type="text" id="userName">

console.log(document.getElementById("userName").value);

//表单取值使用 innerText、innerHTML 都是不行的。

获取/设置HTML 属性

// 格式:document.getElementById(id).attribute=新属性值

let pTags = document.getElementsByTagName("p");
pTags[1].title = "你好!";

console.log(pTags[0].title);

nodeName 属性规定节点的名称

nodeName 是只读的;
元素节点的 nodeName 与标签名相同;
属性节点的 nodeName 与属性名相同;
文本节点的 nodeName 始终是 #text;
文档节点的 nodeName 始终是 #document;

let nodeName = document.getElementsByTagName("body")[0].nodeName;

nodeValue 属性规定节点的值

元素节点的 nodeValue 是 undefined 或 null
文本节点的 nodeValue 是文本本身
属性节点的 nodeValue 是属性值

let element = document.getElementById("divSubmit");
console.log(element.firstChild.nodeValue);

nodeType 属性返回节点的类型

nodeType 是只读的,比较重要的节点类型有:元素-1、属性-2、文本-3、注释-8、文档-9

let element = document.getElementsByTagName("body")[0];
console.log(element.nodeType);// 1

    // 创建元素节点
    let elementNode = document.createElement("Button");
    // 创建文本节点
    let textNode = document.createTextNode("蚩尤后裔");
    // 创建属性节点
    let attributeNode = document.createAttribute("title");
    // 属性节点赋值
    attributeNode.value = "点我";
    // 为元素设置属性
    elementNode.setAttributeNode(attributeNode);

    // 为元素设置样式
    elementNode.style.color = "red";
    elementNode.style.fontFamily = "Arial";
    elementNode.style.fontSize = "larger";

    // 为元素节点添加文本节点
    elementNode.appendChild(textNode);
    // 将元素节点添加到文档中
    // <button title="点我" style="color: red; font-family: Arial; font-size: larger;">蚩尤后裔</button>
    document.body.appendChild(elementNode);

https://gitee.com/wangmx1993/web_app/blob/master/src/main/resources/static/DocumentTest.html

获取元素展示状态,设置元素隐藏与展示

    // 获取元素的style.display属性,如果为"none",表示元素隐藏;否则,元素显示
    document.getElementById("getButtonShowState").onclick = function (ev) {
        if (document.getElementById("china").style.display === "none") {
            console.log("china is hide.");
        } else {
            console.log("china is show.");
        }
    }
    // 在JavaScript中,可以使用style.display属性来控制元素的显示与隐藏。
    // 如果你想显示一个被隐藏的元素,可以将style.display属性设置为''(空字符串,表示使用CSS的默认值)
    // 或'block'、'inline'、'inline-block'等,取决于元素的类型和需求。
    document.getElementById("buttonShow").onclick = function (ev) {
        document.getElementById("china").style.display = "";
    }
    document.getElementById("buttonHide").onclick = function (ev) {
        document.getElementById("china").style.display = "none";
    }

https://gitee.com/wangmx1993/web_app/blob/master/src/main/resources/static/html/%E9%94%AE%E7%9B%98%E7%BB%84%E5%90%88%E4%BA%8B%E4%BB%B6.html

Location 对象

1、Location 对象包含当前 URL 的有关信息,Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问。Location 对象 | 菜鸟教程

Location 对象属性
属性描述
hash设置或返回从井号 (#) 开始的 URL(锚)。
host

设置或返回主机名和当前 URL 的端口号。host 属性是一个可读可写的字符串,可设置或返回当前 URL 的主机名称和端口号部分。

语法:location.host.

这在动态获取服务器Ip与端口时非常有用,比如 H5 中的 WebSocket 连接服务器时,不可能写死服务器的 ip 与端口,此时使用这种方式即可。

hostname

设置或返回当前 URL 的主机名。

hostname 属性是一个可读可写的字符串,可设置或返回当前 URL 的主机名部分。

语法:location.hostname

href设置或返回完整的 URL。
pathname设置或返回当前 URL 的路径部分。
port

设置或返回当前 URL 的端口号。

port 属性是一个可读可写的字符串,可设置或返回当前 URL 的端口部分。

语法:location.port=portnumber

protocol设置或返回当前 URL 的协议。
search设置或返回从问号 (?) 开始的 URL(查询部分)。
<body>
<button id="toBaiDu">前往百度搜索</button>
</body>
<script type="text/javascript">
    // 如果 Url 中是域名,则获取的也是域名, 如果 url 是 ip 地址,则获取的也是 ip地址.
    // 如果 Url 中是省略的 80 的端口,则端口同样返回为空。
    // http://localhost:63342/vue3/static/html/test.html?uid=20201&token=ui99Op67D#Feature
    let href = location.href;
    let protocol = location.protocol;// http:
    let urlHost = window.location.host; // localhost:63342
    let urlHostname = location.hostname;// localhost
    let urlPort = location.port;// 63342
    let hash = location.hash;// #Feature
    let pathname = location.pathname;// /vue3/static/html/test.html
    let search = location.search;// ?uid=20201&token=ui99Op67D
    document.getElementById("toBaiDu").addEventListener("click", function () {
        location.href = "https://www.baidu.com";
    });
</script>
Location 对象方法
属性描述
assign()

加载新的文档。

相当于一个链接,跳转到指定的url,当前页面会转为新页面内容,可以点击后退返回上一个页面。

reload()

重新加载当前文档。语法:location.reload(force)

1、如果该方法没有规定参数,或者参数是 false,它就会用 HTTP 头 If-Modified-Since 来检测服务器上的文档是否已改变。如果文档已改变,reload() 会再次下载该文档。如果文档未改变,则该方法将从缓存中装载文档。这与用户单击浏览器的刷新按钮的效果完全一样

2、如果把该方法的参数设置为 true,那么无论文档的最后修改日期是什么,它都会绕过缓存,从服务器上重新下载该文档。这与用户在单击浏览器的刷新按钮时按住 Shift 健的效果完全一样(强制刷新)

replace()

用新的文档替换当前文档。

replace() 方法不会在 History 对象中生成一个新的记录。当使用该方法时,新的 URL 将覆盖 History 对象中的当前记录。前后两个页面共用一个窗口,所以无法后退返回上一页。

<body>
<button id="ctrlF5">强制刷新</button>
<button id="toBaiDu">百度搜索</button>
</body>
<script type="text/javascript">
    document.getElementById("ctrlF5").addEventListener("click", function () {
        location.reload(true);
    });
    document.getElementById("toBaiDu").addEventListener("click", function () {
        location.replace("http://www.baidu.com");
    });
</script>

History 对象

1、window.history 对象包含浏览器的历史。History 对象 | 菜鸟教程

history.back()与在浏览器点击后退按钮相同,加载历史列表中的前一个 URL。
history.forward()与在浏览器中点击向前按钮相同,加载历史列表中的下一个 URL。
history.go(number) 参数表示跳转页面的个数,例如 history.go(1) 表示前进一个页面,history.go(-1) 表示后退一个页面, go(0) 表示刷新页面。

1、window.navigator 对象包含有关访问者浏览器的信息。

2、来自 navigator 对象的信息具有误导性,不应该被用于检测浏览器版本,这是因为:

  • navigator 数据可被浏览器使用者更改
  • 一些浏览器对测试站点会识别错误
  • 浏览器无法报告晚于浏览器发布的新操作系统
console.log("浏览器代号: " + navigator.appCodeName);// Mozilla
console.log("浏览器名称: " + navigator.appName);// Netscape
console.log("浏览器版本: " + navigator.appVersion);// 5.0 (Windows)
console.log("启用Cookies: " + navigator.cookieEnabled);// true
console.log("硬件平台: " + navigator.platform);// Win32
// Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0
console.log("用户代理: " + navigator.userAgent);
console.log("用户代理语言: " + navigator.language);// zh-CN

页面刷新方式汇总

自动间隔刷新<!-- 3秒之后跳转到百度首页-->
<meta http-equiv="refresh" content="3;url=http://www.baidu.com">
location. href = URLlocation.href = location.href;// 将当前页面地址作为新地址即可刷新当前页面
location.reload( force )

location.reload(); // 相当于按 F5

location.reload( force ) // 相当于按 Ctrl + F5

location.replacelocation.replace(location.href);// 将当前页面地址作为新地址即可刷新当前页面
location.assignlocation.assign(location.href);// 将当前页面地址作为新地址即可刷新当前页面
window.openwindow.open(location.href);// 在新窗口中打开本页面
history.go(x)history.go(0);// go() 里面的参数为0,表示刷新页面
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蚩尤后裔-汪茂雄

芝兰生于深林,不以无人而不芳。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值