原生JS中常用的Window和DOM对象操作汇总

一、常用的Window对象操作

Window对象中又包含了document、history、location、Navigator和screen几个对象,每个对象又有自己的属性方法,这里window可以省略。

如window.location.href  可以简写为location.href


//返回运行浏览器的操作系统和(或)硬件平台
var platform = navigator.platform;
//浏览器的代码名
var appCodeName = navigator.appCodeName;
//浏览器的名称
var appName = navigator.appName;
//浏览器的平台和版本信息
var appVersion = navigator.appVersion;
// alert("platform:"+platform+" appCodeName:"+appCodeName+" appName:"+appName+" appVersion:"+appVersion);

//返回历史列表中的网址数
var length = history.length;

//加载 history 列表中的下一个 URL
history.forward();
//加载 history 列表中的前一个 URL
history.back();
//加载历史列表中的某个具体的页面 -1上一个页面,1前进一个页面
history.go(-1);

//替换当前文档 可以是当前项目根目录下的文档, 或者外部 网址
location.replace("index.html");
location.replace("http://www.baidu.com");

//返回 URL的锚部分 #开始的地方
var hash = location.hash;

//返回一个URL的查询部分 ?之后的部分
var search = location.search;

//返回完整的URL(当前页):
var href = location.href;

//刷新当前文档
location.reload();

//返回屏幕的总宽度和总高度
var width = window.screen.width;
var height = window.screen.height;

//在指定的毫秒数后执行
setTimeout(function(){
//TODO
},30000);

二、常用的HTML DOM操作

//通过getElementById获取input输入的值
var username = document.getElementById("username").value;

//通过querySelector获取input输入的值
var pwd = document.querySelector("#password").value;

//在id为txt的地方添加html
document.getElementById("txt").innerHTML="<h1>Hello World!</h1>";

//返回当前完整的url
var url = document.URL;

//返回当前文档的标题
var title = document.title;

//返回当前文档的域名
var domain = document.domain;

//向输出流写入文本
document.write("Hello World!");
//向输出流写入格式文本
document.write("<h1>Hello World!</h1>");