Home > Web Front-end > JS Tutorial > body text

JavaScript learning summary [6] JS BOM

黄舟
Release: 2017-02-10 09:23:23
Original
1307 people have browsed it

1. Introduction to BOM

The so-called BOM is the Browser Object Model. BOM gives JS the ability to operate the browser, that is, window operation. DOM is used to create and delete nodes and operate HTML documents. There is no formal standard for BOM yet, so each browser has different support for the BOM method, so specific issues need to be dealt with on a case-by-case basis.

2. Window object

The window object is the core of the BOM. The window object refers to the current browser window. All JS global objects, functions, and variables belong to the window object. Global variables are properties of the window object. Global functions are methods of the window object. Even the document of the DOM is one of the properties of the window object, but it can be ignored in most cases.

Window object method:

JavaScript learning summary [6] JS BOM

3. Window operation

 (1) Open window

open() Method can be used to open a new window.

Syntax: window.open(url, name/target, window settings, replace)

The three parameters of this method are optional. By default, a blank page will be opened in a new page. The first parameter sets the path to the window to open. The second parameter specifies where to open the new window and can also be used to specify the name of the window. The third parameter sets the window parameters. Multiple parameters can be separated by commas. If there is a first parameter, the next two parameters can be omitted and a new page will be opened. The second parameter generally does not need to be set. If you want to specify the parameters of the window, there must be a second parameter, which must be '_blank', or replaced by '', and the distance from the top of the screen cannot be 0, otherwise it will be invalid. If it is set The distance to the left and top can be set to 0. The last parameter specifies whether the URL loaded into the window creates an entry in the window's browsing history or replaces the current entry in the browser history. The value is true or false. When the value is true, the URL replaces the current entry in the browsing history. When false the URL creates a new entry in the browsing history.

The following table is some commonly used window setting parameters:

JavaScript learning summary [6] JS BOM

Example: Click the button to open the Baidu homepage in a new window, width 600, height 400, distance There are 0 pixels at the top of the screen and 10 pixels at the left side of the screen.

 <body>
 <input type="button" onClick="newWin()" value="点击我,打开新窗口!">
 <script>
 function newWin(){     window.open(&#39;http://www.baidu.com&#39;, &#39;_blank&#39;, &#39;width=600,height=400,top=0,left=10&#39;); } </script>
 </body>
Copy after login

This example does not open a custom window under IE, but opens a new tab.

If you open a new window directly in the script, it will be directly blocked as an advertising pop-up window under Chrome and FF, but it can be displayed normally under IE. The extreme speed mode of 360 Browser uses the Chrome kernel, and the compatibility mode uses the IE kernel. There are relatively many people using 360 Browser, so I won’t describe it here. As long as other browsers run normally, there will be no problem.

<script>
 window.open(); 
 window.open(&#39;http://baidu.com&#39;); </script>
Copy after login

Example: Gaining focus and losing focus

<body>
 <input type="button" value="获得焦点" onclick="openWin()">
 <script>
 //确保新的窗口获得焦点:
 function openWin(){     var oGet = window.open(&#39;&#39;, &#39;&#39;, &#39;width=400,height=400&#39;);     
 oGet.document.write(&#39;<p>我是新打开的窗口</p>&#39;);     oGet.focus(); } </script>
 
 <input type="button" value="失去焦点" onclick="newWin()">
 <script>
 //确保新的窗口没有获得焦点:
 function newWin(){     var lose = window.open(&#39;&#39;, &#39;&#39;, &#39;width=400,height=300&#39;);     
 lose.document.write(&#39;<p>我是新打开的窗口</p>&#39;);     lose.blur(); } </script>
 </body>
Copy after login

Example: Returning the name of the newly opened window

<body>
 <input type="button" value="打开" onclick="openWin()">
 <script>
 function openWin(){     
 var newWin = window.open(&#39;&#39;, &#39;newWindow&#39;, &#39;width=400,height=300&#39;);     
 newWin.document.write(&#39;<p>新窗口名称:&#39; + newWin.name + &#39;</p>&#39;); } 
 </script>
 </body>
Copy after login

Example: Opening a new window to pass information to the parent window

<body>
 <input type="button" value="打开" onclick="openWin()">
 <script>
 function openWin(){     
 var newWin = window.open(&#39;&#39;, &#39;&#39;, &#39;width=400,height=300&#39;);     
 newWin.document.write(&#39;<p>关闭我之后会向父窗口输入文本信息</p>&#39;);     
 newWin.focus();     
 newWin.opener.document.write(&#39;<p>我是父窗口,加载完成后,向我输出内容会覆盖我所有内容</p>&#39;); } 
 </script>
 </body>
Copy after login

Example: Specify window size, move window and scroll content

 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 </head>
 <body>
 <br><br>
 <h4>用指定像素调整窗口大小:</h4>
 <input type="button" value="打开" onclick="openWin()"><br><br>
 <input type="button" value="调整" onclick="byWin()">
 <script>
 var w; function openWin(){     w=window.open(&#39;&#39;, &#39;&#39;, &#39;width=100,height=100,top=10&#39;);     w.focus(); }     
 function byWin(){     //如果不使用框架,可使用window代替top
     w.top.resizeBy(500,500);     w.focus(); } </script>
 
 <h4>将窗口的大小调整到指定的宽度和高度:</h4>
 <input type="button" value="打开" onclick="newWin()"><br><br>
 <input type="button" value="调整" onclick="toWin()">
 <script>
 var w; function newWin(){     w=window.open(&#39;&#39;, &#39;&#39;, &#39;width=100,height=100&#39;);     w.focus(); } 
 function toWin(){     w.resizeTo(500,500);     w.focus(); } </script>
 
 <h4>相对于当前位置移动新窗口:</h4>
 <input type="button" value="打开" onclick="oWin()"><br><br>
 <input type="button" value="多移动几下" onclick="moveWin()">
 <script>
 var w; function oWin(){     w = window.open(&#39;&#39;, &#39;&#39;, &#39;width=100,height=100&#39;); } 
 function moveWin(){     w.moveBy(200,200);     w.focus(); } </script>
 
 <h4>移动新窗口到指定位置:</h4>
 <input type="button" value="打开" onclick="nWin()"><br><br>
 <input type="button" value="移动" onclick="moveToWin()">
 <script>
 var w; function nWin(){     w=window.open(&#39;&#39;, &#39;&#39;, &#39;width=400,height=300&#39;); } 
 function moveToWin(){     w.moveTo(0,0);     w.focus(); } </script>
 
 <h4>由指定的像素数滚动内容:</h4>
 <input type="button" style="position:fixed;top:0;" onclick="scrollWin()" value="由指定的像素数滚动内容">
 <script>
 function scrollWin(){     window.scrollBy(10,10); } </script>
 
 <h4>滚动到指定内容处:</h4>
 <input type="button" onclick="scrollWindow()" value="滚动到指定内容处">
 <script>
 function scrollWindow(){     window.scrollTo(10,50); } </script>
 
 <br><br><br><br><br><br>
 </body>
 </html>
Copy after login

Method analysis:

resizeBy(w, h): Adjust the size of the window according to the specified pixels. This method defines the pixels by which the lower right corner of the specified window will be moved. The upper left corner will not be moved (it stays at its original coordinates).

This method has two parameters. The first parameter is required and specifies the number of pixels to increase the window width. The optional second parameter specifies the number of pixels by which the window height should be increased. Both parameters can be positive or negative.

resizeTo(w, h): Used to adjust the window size to the specified width and height.

The two parameters of this method are required and are used to specify the width and height of the set window, in pixels.

MoveBy(xnum, ynum): Moves the window by the specified pixels relative to its current coordinates.

This method has two parameters. The first parameter specifies the number of pixels to move the window to the right, and the second parameter specifies the number of pixels to move the window down.

MoveTo(x, y): Moves the upper left corner of the window to a specified coordinate.

This method has two parameters. The first parameter specifies the x coordinate of the new position of the window, and the second parameter specifies the y coordinate of the new position of the window.

scrollBy(xnum, ynum): The content can be scrolled by the specified number of pixels.

This method has two required parameters. The first parameter specifies the number of pixels to scroll the document to the right. The second parameter specifies the number of pixels to scroll the document down.

scrollTo(x, y): Scroll the content to the specified coordinates.

This method has two required parameters. The first one specifies the x coordinate of the document to be displayed in the upper left corner of the window document display area. The second parameter specifies the y-coordinate of the document to be displayed in the upper left corner of the window's document display area.

Example: Print the current page

<body>
 <input type="button" value="打印当前页面" onclick="printpage()">
 <script>
 function printpage(){     window.print(); } </script>
 </body>
Copy after login

(2), close the window

The window.close() method can be used to close the current window.

 //点击按钮关闭当前窗口 <input type="button" value="关闭窗口" onclick="window.close()">
Copy after login

  该方法在 Chrome 下运行正常。IE 下弹窗提示:你查看的网页正在试图关闭选项卡,是否关闭选项卡?点击否,不关闭,点击是,关闭窗口。在 FF 下会报错,因为在 FF 下不允许脚本关闭非脚本打开的窗口,也就是不能关闭一个用户自己打开的窗口,只能关闭由 open 打开的窗口。所以可以先用 open 打开,再关闭,这样就能解决 FF 下不能关闭的问题。这就需要创建两个文档来演示该问题:第二个文档使用上面实例保存为 close.html,第一个文档如下:

//先用open打开保存的文档,然后再点击关闭窗口按钮,效果就达到了 
<input type="button" value="打开窗口" onclick="window.open(&#39;close.html&#39;);">
Copy after login

FF 浏览器的安全机制比较高,不能关闭用户打开的窗口,在网上也没找有找到什么好的办法,只能修改浏览器的默认配置,显然这是不可取的。上面的办法比较笨,另辟蹊跷不能关闭用户打开的,那就自己 open 一个再 close,但这还是比较实在的方法,至少目的是达到了。

  在 IE 下可使用下面的代码关闭当前窗口,不弹窗提示。同时也适用于 Chrome。这里使用 a 标签在 FF 下可以看到报错,使用按钮则没有报错信息。

 <a href="javascript:window.opener=null;window.open(&#39;&#39;, &#39;_self&#39;);window.close();">关闭</a>
Copy after login

  实例:关闭新打开的窗口

<body>
 <input type="button" value="打开" onclick="openWin()">
 <input type="button" value="关闭" onclick="closeWin()">
 <script>
 function openWin(){     
 newWin = window.open(&#39;http://www.baidu.com&#39;,  &#39;&#39;, &#39;width=400,height=300,top=200&#39;); } 
 function closeWin(){     
 newWin.close(); } 
 </script>
 </body>
Copy after login

  实例:检查新窗口是否已关闭

<body>
 <input type="button" value="打开&#39;" onclick="openWin()">
 <input type="button" value="关闭" onclick="closeWin()">
 <input type="button" value="是否关闭" onclick="checkWin()">
 <p id="p1"></p>
 <script>
 var newWin; function openWin(){     
 newWin = window.open(&#39;&#39;, &#39;&#39;, &#39;width=400,height=300,top=200&#39;); } 
 function closeWin(){     
 if(newWin){         
 newWin.close();     
 } } 
 var oP = document.getElementById(&#39;p1&#39;); 
 function checkWin(){     
 if(!newWin){         
 oP.innerHTML = &#39;新窗口还没被打开!&#39;;     
 }     
 else{         
 if(newWin.closed){ 
             
           oP.innerHTML = &#39;新窗口已关闭!&#39;;         
           }         
           else{             
           oP.innerHTML = &#39;新窗口未关闭!&#39;;         
           }     
           }    
 } </script>
 </body>
Copy after login

4、浏览器信息

  window.navigator 对象获取包含有关访问者浏览器的信息。该属性在使用时可以不加 window 前缀。

<body>
 <div id="div1"></div>
 <script>
 txt = &#39;<p>Browser CodeName(浏览器代码名称): &#39; + navigator.appCodeName + &#39;</p>&#39;; 
 txt+= &#39;<p>Browser Name(浏览器名称): &#39; + navigator.appName + &#39;</p>&#39;; 
 txt+= &#39;<p>Browser Version(浏览器版本): &#39; + navigator.appVersion + &#39;</p>&#39;; 
 txt+= &#39;<p>Cookies Enabled(启用Cookies): &#39; + navigator.cookieEnabled + &#39;</p>&#39;; 
 txt+= &#39;<p>Platform(操作平台): &#39; + navigator.platform + &#39;</p>&#39;; 
 txt+= &#39;<p>User-agent header(由客户机发送服务器的 user-agent 头部信息): &#39; + navigator.userAgent + &#39;</p>&#39;; 
 txt+= &#39;<p>User-agent language(客户机代理语言): &#39; + navigator.systemLanguage + &#39;</p>&#39;; 
 document.getElementById(&#39;div1&#39;).innerHTML=txt; </script>
 </body>
Copy after login

  其中最常用的属性是 navigator.userAgent,返回用户代理头的字符串表示(就是包括浏览器版本信息等的字符串),是识别浏览器的关键,可用于获取当前浏览器版本信息,判断浏览器的类型。

<script>
 document.write(navigator.userAgent); 
 </script>
Copy after login

  实例:简单的判断浏览器类型

<script>
 document.write(&#39;操作平台:&#39; + navigator.platform); 
 function userBrowser(){     
 var name = window.navigator.userAgent;     //IE浏览器
     //判断IE和非IE可以使用ActiveXObject,只有IE支持该对象
     //在IE中window.ActiveXObject返回一个对象,则判断为true
     //其他浏览器都返回undefine,两个否返回false,进入或判断,也返回false
     if(!!window.ActiveXObject || &#39;ActiveXObject&#39; in window){         
     return &#39;IE浏览器&#39;;     
     }     
     //FF浏览器
     else if(name.indexOf(&#39;Firefox&#39;) > -1){         
     return &#39;Firefox浏览器&#39;;     
     }     
     //Chrome浏览器
     else if(name.indexOf(&#39;Chrome&#39;) > -1){         
     return &#39;Chrome浏览器&#39;;     }     //Opera浏览器
     else if(name.indexOf(&#39;Opera&#39;) > -1){         
     return &#39;Opera浏览器&#39;;     }     //Safari浏览器
     else if(name.indexOf(&#39;Safari&#39;) > -1){         
     return &#39;Safari浏览器&#39;;     
     }     
     else{         
     return &#39;unknow&#39;;     
     } 
     } 
     alert(&#39;浏览器类型为:&#39; + userBrowser()); 
     </script>
Copy after login

5、页面地址

  window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面,简单说就是可以给赋值,像使用 open 一样。

  语法:location.[属性|方法]

<script>
 //当前页面URL。若中间出现乱码百分号是中文转码后的显示。
 document.write(window.location); </script>
 <input type="button" value="点击查看" onclick="window.location=&#39;http://www.baidu.com&#39;,&#39;_blank&#39;">
 </body>
Copy after login

 location 对象其他应用:

  (1)、location对象属性

    location.hash  设置或返回从井号(#)开始的 URL(锚)。

    location.href  设置或返回完整的 URL。

    location.pathname  设置或返回当前 URL 的路径部分。

    location.host  设置或返回主机名和当前 URL 的端口号。

    location.hostname  设置或返回当前 URL 的主机名,不包含端口。

    location.port  设置或返回当前 URL 的端口号 (80 或 443)。

    location.protocol  返回所使用的 web 协议(http:// 或 https://)。

    location.search  设置或返回从问号(?)开始的 URL(查询部分)。

 (2)、location对象方法

    实例:加载一个新文档

 <input type="button" value="点击加载" onclick="newDoc()">
 <script>
 function newDoc(){     
 window.location.assign(&#39;http://www.baidu.com&#39;) } </script>
Copy after login

    实例:重新载入当前文档

<input type="button" value="点击载入" onclick="reloadPage()">
 <script>
 function reloadPage(){     location.reload() } </script>
Copy after login

    实例:用新的文档替换当前文档

<input type="button" value="点击替换" onclick="replaceDoc()">
 <script>
 function replaceDoc(){     window.location.replace(&#39;http://www.baidu.com&#39;) } </script>
Copy after login

6、浏览器尺寸

  window.screen 对象用于获取用户的屏幕信息。在使用时候可以不加 window 前缀。

  (1)、屏幕分辨率的宽度和高度

  screen.colorDepth 返回用户浏览器表示的颜色位数,通常为32位(每像素的位数)。

  screen.width 和 screen.height 返回屏幕分辨率的宽度和高度。

<script>
 document.write( &#39;屏幕宽度:&#39; + screen.width + &#39;px&#39; ); 
 document.write(&#39;<br>&#39;); 
 document.write( &#39;屏幕高度:&#39; + screen.height + &#39;px&#39; ); 
 </script>
Copy after login

(2)、可用宽度和高度

  screen.availWidth 和 screen.availHeight 返回窗口可以使用的屏幕宽度和高度,不包括窗口任务栏。

  不同系统的窗口任务栏默认高度不一样,任务栏的位置可在屏幕上下左右任何位置,所以有可能可用宽度和高度也不一样。

<script>
 document.write(&#39;可用宽度:&#39; + screen.availWidth +&#39;px&#39;); 
 document.write(&#39;<br>&#39;); 
 document.write(&#39;可用高度:&#39; + screen.availHeight +&#39;px&#39;); 
 </script>
Copy after login

7、工作区尺寸

  (1)、可视区宽度和高度

  获取浏览器窗口尺寸(浏览器的视口,不包括工具栏和滚动条)的方法:

  ①、IE9 以上及现在浏览器都支持:

 

 window.innerWidth  获取浏览器窗口的内部宽度。
  window.innerHeight  获取浏览器窗口的内部高度。
Copy after login

  ②、对于IE9之前可以用:

document.documentElement.clientWidth  表示 HTML 文档所在窗口的当前宽度。
  document.documentElement.clientHeight  表示 HTML 文档所在窗口的当前高度。
Copy after login

  或者可以使用:

 Document 对象的 body 属性对应 HTML 文档的 <body> 标签
  document.body.clientWidth  
  document.body.clientHeight
Copy after login

  在不同浏览器都可以使用的兼容写法:

 var w = document.documentElement.clientWidth || document.body.clientWidth;
  var h = document.documentElement.clientHeight || document.body.clientHeight;
Copy after login
<script> //对于IE9+、Chrome、Firefox、Opera 以及 Safari:
 document.write(&#39;可视宽为:&#39; + window.innerWidth + &#39;<br>&#39;); 
 document.write(&#39;可视高为:&#39; + window.innerHeight + &#39;<br>&#39; + &#39;<br>&#39;); 
 document.write(&#39;可视宽为:&#39; + document.documentElement.clientWidth + &#39;<br>&#39;); 
 document.write(&#39;可视高为:&#39; + document.documentElement.clientHeight + &#39;<br>&#39; + &#39;<br>&#39;); 
 //注意该方法返回的数值与其他不同
 document.write(&#39;可视宽为:&#39; + document.body.clientWidth + &#39;<br>&#39;); 
 document.write(&#39;可视高为:&#39; + document.body.clientHeight + &#39;<br>&#39; + &#39;<br>&#39;); 
 var w = document.documentElement.clientWidth || document.body.clientWidth; 
 var h = document.documentElement.clientHeight || document.body.clientHeight; 
 document.write(&#39;可视宽为:&#39; + w + &#39;<br>&#39; + &#39;可视高为:&#39; + h); 
 </script>
Copy after login

2)、实际网页尺寸

  scrollHeight 和 scrollWidth,获取网页内容高度和宽度。

  scrollHeight 和 scrollWidth 还可获取 DOM 元素中内容实际占用的高度和宽度。

  在 IE 下 scrollHeight 是网页内容实际高度,可以小于 clientHeight。在 FF 下 scrollHeight 是网页内容高度,不过最小值是 clientHeight。也就是说网页内容实际高度小于 clientHeight 时,scrollHeight 返回 clientHeight 。

  在不同浏览器都可以使用的兼容写法:

  var w =document.documentElement.scrollWidth || document.body.scrollWidth;

  var h =document.documentElement.scrollHeight || document.body.scrollHeight;

<script> //兼容性写法
 var w = document.documentElement.scrollWidth || document.body.scrollWidth; 
 var h = document.documentElement.scrollHeight || document.body.scrollHeight; 
 document.write(&#39;网页内容宽为:&#39; + w + &#39;<br>&#39; + &#39;网页内容高为:&#39; + h); 
 </script>
Copy after login

 (3)、包含滚动条的网页尺寸

  offsetHeight 和 offsetWidth,获取网页内容高度和宽度(包括滚动条等边线,会随窗口的显示大小改变)。

  offsetHeight = clientHeight(内容可视区高度) + 滚动条 + 边框。

<script> //兼容性写法
 var w = document.documentElement.offsetWidth || document.body.offsetWidth; 
 var h = document.documentElement.offsetHeight || document.body.offsetHeight; 
 document.write(&#39;网页内容宽为:&#39; + w + &#39;<br>&#39; + &#39;网页内容高为:&#39; + h); 
 </script>
Copy after login

(4)、滚动距离

  所谓滚动距离,就是可视区距离页面顶部滚动了多远,也叫网页卷去的距离。

  scrollTop:设置或获取位于对象最顶端与窗口中可见内容的最顶部之间的距离 ,也就是网页被滚动的高度。

  scrollLeft:设置或获取位于给定对象左边界与窗口中目前可见内容的最左端之间的距离,也就是网页被滚动的宽度。

  offsetTop:获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计算顶部位置,当前对象到其上级顶部的距离,或者距离页面顶部的距离。

  offsetLeft:获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置 ,当前对象到其上级左端的距离,或者距离页面左端的距离。

  offsetTop 和 offsetLeft 不能赋值,设置对象到页面顶部的距离可用 style.top 属性,设置对象到页面左部的距离请用 style.left 属性。

  offsetParent:页面中设置 postion 属性(relative、absolute、fixed)的父容器,从最近的父节点开始,一层层向上找,直到 HTML 的 body。该属性用于获取一个元素用于定位的父级,语法:obj.offsetParent

  实例:滚动页面,点击页面查看滚动距离

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 <script>
 //几款浏览器每次滚动,距离顶部的距离都不一样:
 //在Chrome为100:0-100-200-300-400-500。都是整数递进。
 //而在FF下则为132:0-132-264-396-528。每次递进132。
 //而在IE下则为62:0-62-124-186-248。每次递进则为62。
 window.onload = function (){     
 document.onclick = function (){         
 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;         
 alert(scrollTop);     
 }; 
 }; 
 </script>
 </head>
 <body style="height:2000px">
 </body>
 </html>
Copy after login

该知识点相当重要,而且内容比较混乱,不容易理解,需要做大量练习,巩固所学。

8、浏览器历史记录

  window.history 对象记录了用户曾经浏览过的页面(URL),并可以实现浏览器前进与后退导航的功能。从窗口被打开的那一刻开始记录,每个浏览器窗口、每个标签页乃至每个框架,都有自己的 history 对象与特定的 window 对象关联。在使用时可以不加 window 前缀。

  语法:window.history.[属性|方法]

  (1)、History 对象属性

  历史记录不唯一,所以该对象具有 length 属性,可返回浏览器历史列表中的 URL 数量。

  (2)、History 对象方法

  ①、history.back()  加载 history 列表中的前一个URL,就是返回前一个页面,与浏览器点击后退按钮功能相同。

    该方法等同于:history.Go(-1);

  ②、history.forward()  加载 history 列表中的下一个 URL。就是返回下一个页面,与浏览器的前进按钮功能相同。

    该方法等同于:history.go(1);

  ③、history.go(num)  根据当前所处的页面,加载 history 列表中的某个具体的页面。

    参数说明:1 为前一个,go(1 等价 forward()。0 为当前页面。-1 下一个页面,后一个,go(-1) 等价 back()。

    也可为其他数值,指定要访问的 URL 在 History 的 URL 列表中的相对位置。

    比如:history.go(-2);  返回当前页面之前浏览过的第二个历史页面,相当于点击2次后退按钮。

    history.go(3);  返回当前页面之后浏览过的第三个历史页面。

9、Cookie

  Cookie 用于存储 web 页面的用户信息。就是一些数据,比如自动登录和记住用户名,存储在用户电脑上的文本文件中,方便再次使用。当 web 服务器向浏览器发送 web 页面时,在连接关闭后,服务端不会记录用户的信息。Cookie 的作用就是用于解决 "如何记录客户端的用户信息":当用户访问 web 页面时,他的名字可以记录在 cookie 中。在用户下一次访问该页面时,可以在 cookie 中读取用户访问记录。

  cookie 是以域名为单位的,同一个网站中所有页面共享一套cookie,一般不会超过 50 条,大小为 4k-10k 左右。限制数量和存储大小,这样也阻止了恶意网站给 cookie 中恶意存储,不然一会计算机硬盘就满了。cookie 也是有过期时间的,比如网页中的自动登录,有些为 2 周内,有些为 1 周内,当然过期时间是可以自行定义的,用户也可以自行清理。

  在 JS 中使用 cookie 很简单,就是 document.cookie  该属性可用来创建、读取和删除 cookie。

  语法:名称 = 值

  当浏览器从服务器上请求 web 页面时, 属于该页面的 cookie 会被添加到该请求中。服务端通过这种方式来获取用户的信息。

  提示:跟 cookie 相关的本地测试最好都用 FF,只有 FF 会保存本地的 cookie,其他浏览器都不会保存。在 IE 下也可以测试。

  FF 下查看方法:可点击页面右键 - 查看页面信息 - 安全 - 查看cookie,空白的文件夹就是本地的 cookie。

  (1)、创建和读取cookie

  默认情况下,cookie 属于当前页面并在浏览器关闭时删除。

  ccokie 中的 = 不是赋值,而是添加,可多次添加,并不会发生后面将前面覆盖的情况。

  expires:有效日期,用于指定 cookie 的过期时间。如过不设置,浏览器关闭时 cookie 就被删除了。

  path:可用于设置 cookie 的路径。

  cookie 可直接被读取,或者存储与变量中。

  document.cookie 将以字符串的方式返回所有的 cookie,格式: cookie1=value; cookie2=value; cookie3=value;

  实例:创建用户登录信息,设置 2 周后过期,并读取 cookie

<script> var oD = new Date(); //从当天起14天也就是2周后是几号
 oD.setDate(oD.getDate() + 14); //设置过期时间2周。可在查看cookie中看到user的过期时间为2周后
 document.cookie = &#39;user=小白;expires=&#39; + oD; //浏览器关闭删除本条cookie。pass的过期时间为在会话结束时。
 document.cookie = &#39;pass = 123456&#39;; //读取cookie
 alert(document.cookie); </script>
Copy after login

(2)、修改cookie

  修改 cookie 类似于创建 cookie,新的 cookie 会覆盖旧的 cookie,其实并不能说是被覆盖了,而是新的 cookie 将被添加到 document.cookie 中显示。

 <script> var oD = new Date(); oD.setDate(oD.getDate() + 14); 
 document.cookie = &#39;user=小白;expires=&#39; + oD; document.cookie = &#39;pass=123456&#39;; //可在查看cookie中看到user和pass的内容都被新的cookie替换了
 document.cookie = &#39;user=小明;expires=&#39; + oD; document.cookie = &#39;pass=654321&#39;; //读取cookie
 alert(document.cookie); </script>
Copy after login

 (3)、删除cookie

  删除 cookie 非常简单。只需要设置 expires 参数为以前的时间即可,也就是设置为 -1,昨天过期,浏览器一看这不是已经过期了么,直接删除。

  下面是设置、获取和删除 cookie 的封装函数,方便以后使用。

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>Cookie封装函数</title>
 </head>
 <body>
 <script>
 //设置cookie
 //参数1:cookie的名字,参数2:cookie的值,参数3:cookie过期时间
 function setCookie(name, value, iDay){    
 var oDate = new Date();    
 oDate.setDate(oDate.getDate() + iDay);    
 document.cookie = name + &#39;=&#39; + value + &#39;; expires =&#39; + oDate; } 
 //userName一年后过期,passWord两周后过期。
 setCookie(&#39;userName&#39;, &#39;小白&#39;, 365); 
 setCookie(&#39;passWord&#39;, &#39;123456&#39;, 14); 
 //获取cookie
 //参数为cookie的名称
 function getCookie(name){     //用字符串将cookie分割,注意要用:默认的cookie样式,分号加空格。
     var arr = document.cookie.split(&#39;; &#39;);     
     for(var i=0; i<arr.length; i++){         
     //默认字符串显示为:a=5; b=12; c=21
         //所以用等号再做一次分隔
         var result = arr[i].split(&#39;=&#39;);         
         //result的第一位存名称
         //如果第一位等于name,就说明找到想要的了,就返回第二位的值。
         if(result[0] == name){             
         //result的第二位存值
             return result[1];         }    
              }     
             //如果没有cookie就返回一个空字符串。比如有些用户是第一次进入网站,就没有产生cookie。
     return &#39;&#39;; 
     } 
     //获取cookie中passWord的值
 alert(getCookie(&#39;passWord&#39;)); 
 //参数为删除哪条cookie
 function removeCookie(name){     
 //参数1:cookie的值,1表示随便一个。参数3:昨天过期,立马删除。
     setCookie(name, 1, -1); } 
 //将cookie中userName和passWord删除。
 //在点击查看页面信息,之前保存的cookie就不存在了。
 removeCookie(&#39;userName&#39;); removeCookie(&#39;passWord&#39;); 
 </script>
 </body>
 </html>
Copy after login

  (4)、cookie 小应用:记住上一次的用户名

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>记住上一次的用户名</title>
 <script>
 function setCookie(name, value, iDay){     
 var oDate = new Date();     
 oDate.setDate(oDate.getDate()+iDay);     
 document.cookie = name + &#39;=&#39; + value + &#39;; expires =&#39; + oDate; } function getCookie(name){     
 var arr = document.cookie.split(&#39;; &#39;);     
 for(var i=0; i<arr.length; i++){       
 var result = arr[i].split(&#39;=&#39;);         
 if(result[0] == name){             
 return result[1];         
 }     
 }     
 return &#39;&#39;; } 
 function removeCookie(name){     
 setCookie(name, 1, -1); } 
 window.onload = function (){     
 var oForm = document.getElementById(&#39;form1&#39;);     
 var oUser = document.getElementsByName(&#39;user&#39;)[0];     //在点击提交按钮时发生的事件
     oForm.onsubmit = function (){         //创建一个cookie,值为用户名输入的值,14天后过期
         setCookie(&#39;user&#39;, oUser.value, 14);     };     //用户名的值为获取cookie中的user
     oUser.value = getCookie(&#39;user&#39;); }; </script>
 </head>
 <body>
 //index.html为本文档文件名 <form id="form1" action="index.html">
     用户名:<input type="text" name="user"><br>
     密 码:<input type="password" name="pass"><br>
     <input type="submit" name="" value="登录">
 </form>
 </body>
 </html>
Copy after login

以上就是 JavaScript学习总结【6】JS BOM的内容,更多相关内容请关注PHP中文网(www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!