- 所有浏览器都支持window对象,它表示浏览器窗口本身;
- 所有 JavaScript 全局对象、全局函数以及全局变量均自动成为 window 对象的成员
- 全局变量是window对象的属性,全局函数是window对象的方法;
- document也是window对象的属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.code{
color: gray;
border: 1px solid gainsboro;
font-size: 15px;
}
pre{
margin: 1em 0em 1em -19em;
font-family: "楷体";
}
.result{
color: gray;
background-color: ghostwhite;
font-size: 16px;
padding: 0.5em 1em;
}
h3{
color: red;
}
.result span:first-child{
display: block;
float: left;
width: 10em;
color: black;
}
</style>
<script type="text/javascript">
function objDisplay(eleId,obj){
if(typeof(eleId)!="string" || typeof(obj)!="object"){
alert("Function objDisplay() need the first parameter string and second object !")
}else{
var ele = document.getElementById(eleId);
if(!ele || !obj){
alert("Please check the parameter !")
}else{
for(i in obj){
var div = document.createElement("div");
for(var j=0;j<2;j++){
var span = document.createElement("span");
if(j==0) span.innerHTML = i+" : ";
else span.innerHTML = obj[i];
div.appendChild(span);
}
ele.appendChild(div);
}
}
}
}
</script>
</head>
<body>
<ul>
<li>
<h3>window</h3>
<h4>代码:</h4>
<div class="code">
<pre>
//window属性和方法
var winDict = {
"windowWidth":window.innerWidth,
"windowHeight":window.innerHeight,
"window.open()":"打开新窗口",
"window.close()":"关闭当前窗口",
"window.moveTo()":"移动当前窗口",
"window.resizeTo()":"调整当前窗口的尺寸"
}
//涵盖所有浏览器的写法(浏览器的视口,不包括工具栏和滚动条)
var winHeight = window.innerHeight
||document.documentElement.clientWidth
||document.body.clientWidth;
var winWidth = window.innerWidth
||document.documentElement.clientWidth
||document.body.clientWidth;
objDisplay("winDict",winDict);
</pre>
</div>
<h4>结果:</h4>
<div id="winDict" class="result"></div>
<hr />
<script>
//window属性和方法
var winDict = {
"windowWidth":window.innerWidth,
"windowHeight":window.innerHeight,
"window.open()":"打开新窗口",
"window.close()":"关闭当前窗口",
"window.moveTo()":"移动当前窗口",
"window.resizeTo()":"调整当前窗口的尺寸"
}
//涵盖所有浏览器的写法(浏览器的视口,不包括工具栏和滚动条)
var winHeight = window.innerHeight
||document.documentElement.clientWidth
||document.body.clientWidth;
var winWidth = window.innerWidth
||document.documentElement.clientWidth
||document.body.clientWidth;
objDisplay("winDict",winDict);
</script>
</li>
</ul>
</body>
</html>
image.png
- window.screen 对象在实际写的时候,可以不写window;
- screen.availWidth/screen.availHeight 属性返回访问者屏幕的宽度/高度,以像素计,减去界面特性,比如窗口任务栏;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.code{
color: gray;
border: 1px solid gainsboro;
font-size: 15px;
}
pre{
margin: 1em 0em 1em -19em;
font-family: "楷体";
}
.result{
color: gray;
background-color: ghostwhite;
font-size: 16px;
padding: 0.5em 1em;
}
h3{
color: red;
}
.result span:first-child{
display: block;
float: left;
width: 10em;
color: black;
}
</style>
<script type="text/javascript">
function objDisplay(eleId,obj){
if(typeof(eleId)!="string" || typeof(obj)!="object"){
alert("Function objDisplay() need the first parameter string and second object !")
}else{
var ele = document.getElementById(eleId);
if(!ele || !obj){
alert("Please check the parameter !")
}else{
for(i in obj){
var div = document.createElement("div");
for(var j=0;j<2;j++){
var span = document.createElement("span");
if(j==0) span.innerHTML = i+" : ";
else span.innerHTML = obj[i];
div.appendChild(span);
}
ele.appendChild(div);
}
}
}
}
</script>
</head>
<body>
<ul>
<li>
<h3>screen</h3>
<h4>代码:</h4>
<div class="code">
<pre>
//screen属性
var scrDict = {
"availWidth":window.screen.availWidth,
"windowHeight":screen.availHeight,
}
objDisplay("winDict",scrDict);
</pre>
</div>
<h4>结果:</h4>
<div id="winDict" class="result"></div>
<hr />
<script>
//screen属性
var scrDict = {
"availWidth":window.screen.availWidth,
"windowHeight":screen.availHeight,
}
objDisplay("winDict",scrDict);
</script>
</li>
</ul>
</body>
</html>
image.png
- window.location 对象用于获得当前页面的地址 (URL),并可以把浏览器重定向到新的页面;
- window.location 对象在编写时可不使用 window 这个前缀;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.code{
color: gray;
border: 1px solid gainsboro;
font-size: 15px;
}
pre{
margin: 1em 0em 1em -19em;
font-family: "楷体";
}
.result{
color: gray;
background-color: ghostwhite;
font-size: 16px;
padding: 0.5em 1em;
}
h3{
color: red;
}
.result span:first-child{
display: block;
float: left;
width: 10em;
color: black;
}
button{
background-color: blueviolet;
color: white;
border: 2px solid plum;
border-radius: 2em;
padding: 0.5em;
margin: 0.5em;
}
button:focus{
color: bisque;
}
</style>
<script type="text/javascript">
function objDisplay(eleId,obj){
if(typeof(eleId)!="string" || typeof(obj)!="object"){
alert("Function objDisplay() need the first parameter string and second object !")
}else{
var ele = document.getElementById(eleId);
if(!ele || !obj){
alert("Please check the parameter !")
}else{
for(i in obj){
var div = document.createElement("div");
for(var j=0;j<2;j++){
var span = document.createElement("span");
if(j==0) span.innerHTML = i+" : ";
else span.innerHTML = obj[i];
div.appendChild(span);
}
ele.appendChild(div);
}
}
}
}
</script>
</head>
<body>
<ul>
<li>
<h3>location</h3>
<h4>代码:</h4>
<div class="code">
<pre>
//location属性
var lcaDict = {
"hostname":window.location.hostname,//返回 web 主机的域名
"pathname":location.pathname,//返回当前页面的路径和文件名
"port":location.port,//返回 web 主机的端口
"protocol":location.protocol,//返回所使用的 web 协议(http:// 或 https://)
"href":location.href,//属性返回当前页面的 URL
}
objDisplay("lcaDict",lcaDict);
</pre>
</div>
<h4>结果:</h4>
<div id="lcaDict" class="result"></div>
<!--location.assign() 方法加载新的文档-->
<button onclick="location.assign('https://www.jianshu.com/')">Assign</button>
<hr />
<script>
//location属性
var lcaDict = {
"hostname":window.location.hostname,//返回 web 主机的域名
"pathname":location.pathname,//返回当前页面的路径和文件名
"port":location.port,//返回 web 主机的端口
"protocol":location.protocol,//返回所使用的 web 协议(http:// 或 https://)
"href":location.href,//属性返回当前页面的 URL
}
objDisplay("lcaDict",lcaDict);
</script>
</li>
</ul>
</body>
</html>
image.png
- history.back()方法加载历史列表中的前一个 URL,与在浏览器点击后退按钮相同;
- history.forward()方法加载历史列表中的下一个 URL,与在浏览器中点击按钮向前相同;
- window.history 对象在编写时可不使用 window 这个前缀
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.code{
color: gray;
border: 1px solid gainsboro;
font-size: 15px;
}
pre{
margin: 1em 0em 1em -19em;
font-family: "楷体";
}
.result{
color: gray;
background-color: ghostwhite;
font-size: 16px;
}
ul li h3{
color: red;
}
button{
background-color: blueviolet;
color: white;
border: 2px solid plum;
border-radius: 2em;
padding: 0.5em;
margin: 0.5em;
}
button:focus{
color: bisque;
}
</style>
</head>
<body>
<ul>
<li>
<h3>history</h3>
<h4>代码:</h4>
<div class="code">
<pre>
<button name="back" onclick="window.history.back()">back</button>
<button name="forward" onclick="history.forward()">forward</button>
</pre>
</div>
<h4>结果:</h4>
<div class="result">
<button name="back" onclick="window.history.back()">back</button>
<button name="forward" onclick="history.forward()">forward</button>
</div>
</li>
<hr />
</ul>
</body>
</html>
image.png
- window.navigator 对象包含有关访问者浏览器的信息;
- window.navigator 对象在编写时可不使用 window 这个前缀
- 来自 navigator 对象的信息具有误导性,不应该被用于检测浏览器版本
navigator 数据可被浏览器使用者更改;
浏览器无法报告晚于浏览器发布的新操作系统;
- 使用对象来检测浏览器,例:由于只有 Opera 支持属性 "window.opera",可以据此识别出 Opera
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.code{
color: gray;
border: 1px solid gainsboro;
font-size: 15px;
}
pre{
margin: 1em 0em 1em -19em;
font-family: "楷体";
}
.result{
color: gray;
background-color: ghostwhite;
font-size: 16px;
padding: 0.5em 1em;
}
h3{
color: red;
}
.result span:first-child{
display: block;
float: left;
width: 10em;
color: black;
}
</style>
<script type="text/javascript">
function objDisplay(eleId,obj){
if(typeof(eleId)!="string" || typeof(obj)!="object"){
alert("Function objDisplay() need the first parameter string and second object !")
}else{
var ele = document.getElementById(eleId);
if(!ele || !obj){
alert("Please check the parameter !")
}else{
for(i in obj){
var div = document.createElement("div");
for(var j=0;j<2;j++){
var span = document.createElement("span");
if(j==0) span.innerHTML = i+" : ";
else span.innerHTML = obj[i];
div.appendChild(span);
}
ele.appendChild(div);
}
}
}
}
</script>
</head>
<body>
<ul>
<li>
<h3>navigator</h3>
<h4>代码:</h4>
<div class="code">
<pre>
//navigator属性
var navDict = {
"appCodeName":window.navigator.appCodeName,
"appName":navigator.appName,
"appVersion":navigator.appVersion,
"cookieEnabled":navigator.cookieEnabled,
"platform":navigator.platform,
"userAgent":navigator.userAgent,
"systemLanguage":navigator.systemLanguage,
}
objDisplay("navDict",navDict);
</pre>
</div>
<h4>结果:</h4>
<div id="navDict" class="result"></div>
<hr />
<script>
//navigator属性
var navDict = {
"appCodeName":window.navigator.appCodeName,
"appName":navigator.appName,
"appVersion":navigator.appVersion,
"cookieEnabled":navigator.cookieEnabled,
"platform":navigator.platform,
"userAgent":navigator.userAgent,
"systemLanguage":navigator.systemLanguage,
}
objDisplay("navDict",navDict);
</script>
</li>
</ul>
</body>
</html>
image.png
- JavaScript中消息框有三种:警告框,确认框,提示框;
- 警告框alert(),警告框携带信息弹出,需点击"确认"按钮后,才能继续进行下一步操作;
- 确认框confirm(),确认框携带信息弹出,点击"确认"按钮后返回true,点击"取消"按钮后返回false
- 提示框prompt(),提示框携带信息弹出,且要求用户输入内容,若未输入或点击"取消"按钮,则返回null,若输入且点击"确定"按钮,则返回输入值
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.code{
color: gray;
border: 1px solid gainsboro;
font-size: 15px;
}
pre{
margin: 1em 0em 1em -19em;
font-family: "楷体";
}
.result{
color: gray;
background-color: ghostwhite;
font-size: 16px;
}
ul li h3{
color: red;
}
button{
background-color: blueviolet;
color: white;
border: 2px solid plum;
border-radius: 2em;
padding: 0.5em;
margin: 0.5em;
}
button:focus{
color: bisque;
}
</style>
</head>
<body>
<ul>
<li>
<h3>PopupAlert</h3>
<h4>代码:</h4>
<div class="code">
<pre>
<button name="alert" onclick="alert('Hello World !')">Alert</button>
<button name="confirm" onclick="confirmResult()">Confirm</button>
<button name="prompt" onclick="promptResult()">Prompt</button>
</pre>
</div>
<h4>结果:</h4>
<div class="result">
<button name="alert" onclick="alert('Hello World !')">Alert</button>
<button name="confirm" onclick="confirmResult()">Confirm</button>
<button name="prompt" onclick="promptResult()">Prompt</button>
</div>
<div class="result">
<p id="confirmRes">显示Confirm按钮点击后的结果!</p>
<p id="promptRes">显示Prompt按钮点击后输入的结果!</p>
</div>
</li>
<hr />
<script>
function confirmResult(){
var result = confirm("Continue ?");
document.getElementById("confirmRes").innerHTML = result;
}
function promptResult(){
var result = prompt("Please input the infomation !");
document.getElementById("promptRes").innerHTML = result;
}
</script>
</ul>
</body>
</html>
test27.gif
- setTimeout(),定时任务,在多长时间后,执行一次,只执行一次;
- clearTimeout(),清除定时任务.
- setInterval(),重复任务,每隔多长时间,就执行一次,重复执行;
- clearInterval(),清除重复任务.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.code {
color: gray;
border: 1px solid gainsboro;
font-size: 15px;
}
pre {
margin: 1em 0em 1em -19em;
font-family: "楷体";
}
.result {
color: gray;
background-color: ghostwhite;
font-size: 16px;
}
ul li h3 {
color: red;
}
button {
background-color: blueviolet;
color: white;
border: 2px solid plum;
border-radius: 2em;
padding: 0.5em;
margin: 0.5em;
}
button:focus {
color: bisque;
}
</style>
</head>
<body>
<ul>
<li>
<h3>timing</h3>
<h4>代码:</h4>
<div class="code">
<pre>
//定义全局变量
var initDate = "";
var nowDateAll = "";
//时钟
function dateDisRef() {
var now = new Date(); //定义当前时间
var dateAll = "";
//定义时间字典
var dateDict = {
"year": now.getFullYear(),
"month": now.getMonth() + 1,
"day": now.getDate(),
"hours": now.getHours(),
"minutes": now.getMinutes(),
"seconds": now.getSeconds()
}
//格式校验,不足十的,在前方补0
function checkDate(dateTime, dateDict) {
if(dateDict[dateTime] < 10) {
dateDict[dateTime] = "0" + dateDict[dateTime];
}
}
//日期展示
for(dateTime in dateDict) {
checkDate(dateTime, dateDict);
switch(dateTime) {
case "year":
case "month":
dateAll += (dateDict[dateTime] + "-");
break;
case "hours":
case "minutes":
dateAll += (dateDict[dateTime] + ":");
break;
case "day":
dateAll += (dateDict[dateTime] + " ");
break;
case "seconds":
dateAll += dateDict[dateTime];
default:
break;
}
}
document.getElementById("dateDis").innerHTML = dateAll;
nowDateAll = dateAll;
//只设置一次
if(initDate == "") {
//替换第一个空格为T,用来设置日历默认时间
initDate = dateAll.replace(" ", "T");
}
//定时任务,等待500ms,执行dateDisRef()方法,调用后再次等待500ms,再会进行下次调用,故刷新频率为1s
var timeOut = setTimeout('dateDisRef()', 500);
}
//调用方法
dateDisRef();
//设置日历默认时间为当前时间
document.getElementById("initDate").value = initDate;
//倒计时
var interval;
function timing() {
//获得日历时间,并进行格式转换
var calendarTime = document.getElementById("initDate").value.toString();
//进行同时区时间设置(防止时差问题,导致时间差错误),均设置为标准时区
var calendarDate = new Date(calendarTime + "Z");
//动态获取当前时间
var nowDate = new Date(nowDateAll + "Z");
//将时间差转化为s
var dateMius = (calendarDate - nowDate) / 1000;
//清除重复任务,防止生成多个
clearInterval(interval);
//定义重复任务,时间间隔1s
interval = setInterval(function() {
dateMius--;
var timingEle = document.getElementById("timing");
if(dateMius == 0) {
timingEle.innerHTML = "倒计时结束!";
timingEle.style.color = "red";
clearInterval(interval);
} else {
if(timingEle.style.color == "red") timingEle.style.color = "gray";
timingEle.innerHTML = dateMius + " S";
}
}, 1000);
}
</pre>
</div>
<h4>结果:</h4>
<div class="result">
<p id="dateDis"></p>
</div>
<div class="result">
<input type="datetime-local" id="initDate" onchange="timing()" />
<p id="timing"></p>
</div>
<script>
//定义全局变量
var initDate = "";
var nowDateAll = "";
//时钟
function dateDisRef() {
var now = new Date(); //定义当前时间
var dateAll = "";
//定义时间字典
var dateDict = {
"year": now.getFullYear(),
"month": now.getMonth() + 1,
"day": now.getDate(),
"hours": now.getHours(),
"minutes": now.getMinutes(),
"seconds": now.getSeconds()
}
//格式校验,不足十的,在前方补0
function checkDate(dateTime, dateDict) {
if(dateDict[dateTime] < 10) {
dateDict[dateTime] = "0" + dateDict[dateTime];
}
}
//日期展示
for(dateTime in dateDict) {
checkDate(dateTime, dateDict);
switch(dateTime) {
case "year":
case "month":
dateAll += (dateDict[dateTime] + "-");
break;
case "hours":
case "minutes":
dateAll += (dateDict[dateTime] + ":");
break;
case "day":
dateAll += (dateDict[dateTime] + " ");
break;
case "seconds":
dateAll += dateDict[dateTime];
default:
break;
}
}
document.getElementById("dateDis").innerHTML = dateAll;
nowDateAll = dateAll;
//只设置一次
if(initDate == "") {
//替换第一个空格为T,用来设置日历默认时间
initDate = dateAll.replace(" ", "T");
}
//定时任务,等待500ms,执行dateDisRef()方法,调用后再次等待500ms,再会进行下次调用,故刷新频率为1s
var timeOut = setTimeout('dateDisRef()', 500);
}
//调用方法
dateDisRef();
//设置日历默认时间为当前时间
document.getElementById("initDate").value = initDate;
//倒计时
var interval;
function timing() {
//获得日历时间,并进行格式转换
var calendarTime = document.getElementById("initDate").value.toString();
//进行同时区时间设置(防止时差问题,导致时间差错误),均设置为标准时区
var calendarDate = new Date(calendarTime + "Z");
//动态获取当前时间
var nowDate = new Date(nowDateAll + "Z");
//将时间差转化为s
var dateMius = (calendarDate - nowDate) / 1000;
//清除重复任务,防止生成多个
clearInterval(interval);
//定义重复任务,时间间隔1s
interval = setInterval(function() {
dateMius--;
var timingEle = document.getElementById("timing");
if(dateMius == 0) {
timingEle.innerHTML = "倒计时结束!";
timingEle.style.color = "red";
clearInterval(interval);
} else {
if(timingEle.style.color == "red") timingEle.style.color = "gray";
timingEle.innerHTML = dateMius + " S";
}
}, 1000);
}
</script>
</li>
<hr />
</ul>
</body>
</html>
image.png
test28.gif
- cookie 是存储于访问者的计算机中的变量。每当同一台计算机通过浏览器请求某个页面时,就会发送这个 cookie
-
名字 cookie
当访问者首次访问页面时,他或她也许会填写他/她们的名字。名字会存储于 cookie 中。当访问者再次访问网站时,他们会收到类似 "Welcome John Doe!" 的欢迎词。而名字则是从 cookie 中取回的。
密码 cookie
当访问者首次访问页面时,他或她也许会填写他/她们的密码。密码也可被存储于 cookie 中。当他们再次访问网站时,密码就会从 cookie 中取回。
日期 cookie
当访问者首次访问你的网站时,当前的日期可存储于 cookie 中。当他们再次访问网站时,他们会收到类似这样的一条消息:"Your last visit was on Tuesday August 11, 2005!"。日期也是从 cookie 中取回的。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body onload="checkCookie()">
<script>
//设置cookie
function setCookies(name,value,expiredays){
var exdate = new Date();
//设置失效日期
exdate.setDate(exdate.getDate()+expiredays);
//设置cookie格式 name=value;expires=exdate
//escape()用来编码字符串 toGMTString()此日期会在转换为字符串之前由本地时区转换为 GMT时区
document.cookie=name+"="+escape(value)+((expiredays==null)?"":(";expires="+exdate.toGMTString()));
}
//获取cookie
function getCookies(name){
//判断cookie的长度
if(document.cookie.length>0){
//获取要获取cookie的起始位置
start = document.cookie.indexOf(name+"=");
//判断indexOf()搜索结果,无结果时为-1
if(start!=-1){
start = start+name.length+1;//设置起始值为=的位置
end = document.cookie.indexOf(";",start);//从起始值搜索到名字的结束
if(end==-1) end=document.cookie.length;//无失效日期,则取到尾
return unescape(document.cookie.substring(start,end));//解码截取的子字符串
}
}
return "";
}
//检查是否设置了cookie
function checkCookie(){
usrName = getCookies("usrName");//获取usrCookie
//不为空弹出欢迎框
if(usrName!=null && usrName!=""){
alert("Welcome again "+usrName+" !");
}else{
//为空则弹出消息框,提示用户输入名字,并设置cookie
usrName=prompt("Please enter your name :","");
if(usrName!=null&&usrName!=""){
setCookies("usrName",usrName,30);
}
}
}
</script>
</body>
</html>
test29.gif
网友评论