Home  >  Article  >  Web Front-end  >  Summary of basic knowledge of BOM in JavaScript

Summary of basic knowledge of BOM in JavaScript

高洛峰
高洛峰Original
2017-02-17 17:21:261153browse

1. What is BOM

BOM (Browser Object Document) is the browser object model.

BOM provides objects that interact with browser windows independently of content;

Since BOM is mainly used to manage communication between windows, its core object is window;

BOM is composed of a series of related objects, and each object provides many methods and properties;

BOM lacks standards. The standardization organization for JavaScript syntax is ECMA, and the standardization organization for DOM is W3C , the BOM was originally part of the Netscape browser standard.

2. What to learn when learning BOM

We will learn some objects that interact with the browser window, such as the window object that can move and resize the browser, and the location object that can be used for navigation. With the history object, the navigator and screen objects can obtain the browser, operating system and user screen information. You can use the document as the entrance to access the HTML document, manage the frames object of the frame, etc. Here, I only introduce some basic knowledge of window objects, etc., and some ECMAscript knowledge will also be explained. Other objects Location, Screen, Navigator, and History are not introduced in detail one by one. .

3. Window object

The window object is the top-level object in js. All variables and functions defined in the global scope will become the properties and methods of the window object when called. The window can be omitted.

Example:

打开窗口 window.open(url,target,param);
// url 要打开的地址
//target 新窗口的位置 _blank _self _parent(父框架)
//param 新窗口的一些设置
//返回值,新窗口的句柄
关闭窗口:window.close();

4. BOM fragmentary knowledge (window object)

1. Timer

Delayed execution setTimeout([string | function] code, interval);
clearTimeout([number] intervalId);

 <body>
 <input type="button" value="closeTimerId" id="btn">
 <script>
 var btn = document.getElementById("btn");
 var timerId = setTimeout(function () {
  alert("23333");
 }, 3000);
 btn.onclick = function () { //在设置的时间之前(3s内)点击可以取消定时器
  clearTimeout(timerId);
 }
 </script>
 </body>

Timing execution var timerId = setInterval(code, interval);
clearInterval(timerId); //Clear timer

Countdown case:

<body>
<input type="button" value="倒计时开始10" id="btn" disabled/>
<script>
 var btn = document.getElementById("btn");
 var num = 10;
 var timerId = setInterval(function () {
  num--;
  btn.value = "到时器开始" + num;
 if (num == 0) {
  clearInterval(timerId);
  btn.disabled = false;
  btn.value = "同意,可以点了";
 }
 },1000);
 </script> 
 </body>

2 .offset series methods

offsetWidth and offsetHeight

The composition of offsetHeight

offsetHeight = height + padding + border

offsetWidth is the same

offsetHeight The difference with style.height

1. demo.style.height can only obtain inline styles, otherwise it cannot be obtained

2. .style.height is a string (with unit px), offsetHeight is a numerical value (no unit)

3. .style.height can set the inline style, but offsetHeight is a read-only property and cannot be set

So: demo.style.height gets the value of an element Real height/width, use .style.height to set the height/width

offsetLeft and offsetTop

The composition of offsetLeft

1, to the closest to itself (with positioning ) the left/top of the parent element

2, if all parent elements are not positioned, the body shall prevail

3, offsetLeft is from the left side of its own border to the left side of the parent padding Side distance

The difference between offsetLeft and style.left

1, style.left can only obtain inline styles

2, offsetLeft is read-only, style.left is readable Write

3, offsetLeft is a numerical value, style.left is a string and has the unit px

4. If there is no positioning, the value obtained by style.left may be invalid

5, the biggest difference: offsetLeft is based on the upper left corner of the border, style.left is based on the upper left corner of margin

offsetParent composition

1. Return the closest positioning of the object Parent element

2. If all parent elements of the current element are not positioned (position is absolute or relative), then offsetParent is body

3. What offsetLeft obtains is relative to offsetParent The difference between distance

and parentNode

parentNode always points to the nearest parent element of the current element, regardless of whether it is positioned or not

3.scroll series method

scrollHeight and scrollWidth The height/width of the actual content inside the object (excluding the border)

scrollTop and scrollLeft The distance from the top/left side of the scrolled part to the top/left side of the visual area

onscroll event Events triggered by scroll bar scrolling

Page scroll coordinates var scrollTop = window.pageYoffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

4 .client series

clientX and clientY Get the position of the mouse in the visual area clientX = width + padding, clientY = height + padding

clientLeft The width of the border, including scrolling if there is a scroll bar Article

Example: Get the size of the visible area of ​​the page

function client() {
  return {
   clientWidth: window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth || 0;
    clientHeight: window.innerHeight || document.body.clientHeitght || document.documentElement.clientHeight || 0;
  };
 }

5. Event parameter e

When the event occurs , the system will automatically pass a parameter to the event processing function and provide some data related to the event. The event parameter e browser compatibility detection: e = e || window.event

e.pageX and e .pageY

获取鼠标在页面中的位置(IE8中不支持pageX和pageY,支持window.event获取参数事件)        pageX = clientX + 页面滚动出去的距离

6.获得计算后样式的方法

w3c标准        window.get ComputedStyle(element, null)[属性]IE浏览器        element.currentStyle[属性]封装浏览器兼容性函数 

function getStyle(element, attr) {
 if(window.getComputedStyle) {
  return window.getComputedStyle(element, null)[attr];
 } else {
  return element.currentStyle[attr];
 }
 }

7.事件补充

注册事件

注册事件的性能问题

移除事件

事件冒泡

事件捕获  事件的三个阶段

事件对象的常见属性

DOM笔记里有提到注册事件和移除事件,这里着重讲事件对象,事件对象的常见属性

7.1 target 和currentTarget

target        始终是点击的元素(IE8及之前是srcElement)

currentTarget        执行事件处理函数的元素

this        始终和currentTarget一样

7.2 事件冒泡

用addEventListener注册事件的时候,第三个参数是false,即是冒泡。

冒泡的好处 - 事件委托

从一个例子中说明

 <body>
 <ul id="ul">
 <li>我是第1个li标签</li>
 <li>我是第2个li标签</li>
 <li>我是第3个li标签</li>
 <li>我是第4个li标签</li>
 </ul>
 <input type="button" value="insertLi" id="btn">
 <script>
 var ul = document.getElementById("ul");
 var btn = document.getElementById("btn");
 //把本来应该给li注册的事件,委托给ul,只需要给一个元素注册事件
 //动态创建的li,也会执行预期的效果
 ul.addEventListener("click", test, false); //注册点击事件
 btn.onclick = function () { //点击同样会有alert
  var li = document.createElement("li");
  li.innerHTML = "我是新插入的li标签";
  ul.appendChild(li);
 };
 //函数写在注册事件代码之外,提高性能
 function test(e) {
  alert(e.target.innerText);
 }
 </script>
 </body>

当事件冒泡影响到了其他功能的实现时,需要阻止冒泡    

e.stopPropagation( )        IE8及之前:   event.cancleBubble = true;

阻止默认行为的执行

e.preventDefault()        IE8及之前:  event.returnValue = false;

看一下阻止跳转到百度的例子:

<body>
 <a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" id="link">百度</a>
 <script>
 var link = document.getElementById("link");
 link.addEventListener("click", fn, false);
 function fn(e) {
  e.preventDefault();
  //若用return false; 不起作用,若用link.onclick = function();return false可以阻止
 }
 </script>
 </body>

7.3 鼠标事件的参数

e.type        事件的类型,如click,mouseover

事件的3个阶段        1 捕获阶段 2 目标阶段 3 冒泡阶段

e.eventPhase        事件阶段

shiftKey/ctrlKey/altKey        按下鼠标同时按下组合键

button        获取鼠标的按键

e.clientX和e.clientY        获取鼠标在可视区域的位置

还有7.2中的取消事件冒泡和阻止默认行为的执行

8.正则表达式

定义:

正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。

规则:

1 元字符       
        .   匹配任何单个字符,除了换行
        d  数字   \D 非数字       [0-9]        w  数字 字母 下划线   \W 非     [0-9a-zA-Z_]        \s  空白   \S 非空白
        \n  换行
        \t  制表符

2 范围-- 匹配的是一个字符        [0-9][0123][a-z][A-Z]  匹配的是一个字符

3 | 或者        | 或者

4 量词  -只修饰一个字符 

        a+  1个或多个a
        a?   1个或0个a
        a*   0个或多个a
   a{x}  x个n
   a{x,} 至少x个a
   a{x,y}  x-y个a

5 开始结束     

          ^a  以a开始
          a$  以a结束

6 ( ) 看成是一个整体,即分组 

7 匹配汉字        [\u4e00-\u9fa5]8 参数

i  忽略大小写
g 全局匹配

9 ^在[ ]中的作用——取反 

10 贪婪模式和非贪婪模式

默认情况  贪婪模式  <.+>
非贪婪模式  <.+?>

8.1 正则表达式对象RegExp

<body>
 <a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" id="link">百度</a>
 <script>
 // var regularExpression = new RegExp("\\d"); //第一种写法
 var regularExpression = /\d/; //第二种写法
 var str = "adfj23dald";
 console.log(regularExpression.test(str)); //test就是匹配方法,结果是true
 </script>
 </body>

8.2 正则之匹配

例:验证电子邮箱

//验证电子邮箱
 // abc@sohu.com
 // 11111@qq.com
 // aaaaa@163.com
 // abc@sina.com.cn 
 var reg = /^\w+@\w+\.\w+(\.\w+)?$/;
 var str = "abc@sina.com.cn";
 console.log(reg.test(str));

8.3 正则之提取

例:找数字

 var str = "张三: 1000,李四:5000,王五:8000。";
 var reg = /\d+/g;
 //默认情况下,找到第一个匹配的结果就返回,后面加个g,就是全局找
 var arr = str.match(reg);
 console.log(arr);

8.4 正则之替换

例:所有的逗号替换成句号

 var str = "abc,efg,123,abc,123,a";
 str = str.replace(/,/g,".");
 console.log(str);

8.5 正则的分组( )

在正则表达式中用( )把要分到一组的内容括起来,组分别是RegExp.$1    RegExp.$2等等

例:交换位置  源字符串"5=a, 6=b, 7=c"  要的结果"a=5, b=6, c=7"

var str = "5=a, 6=b, 7=c";
str = str.replace(/(\d+)=(\w+)/g, "$2=$1");
console.log(str);

9.键盘事件对象[b][/b]

方法

keydown  按下时

keypress  按下

keyup  抬起时

属性

keyCode  键盘码,只有数字和字母对应ASCII码

charCode  对应ASCII码,只有在keypress中才生效(IE9+)

例:在切换鼠标焦点时,用enter键代替tab键

<body>
 <input type="text"><input type="text"><input id="t1" type="text"><input type="text"><input type="text"><input type="text"><inputtype="text"><input type="text"><input type="text"><input type="text">
 <script>
 var inputs = document.body.getElementsByTagName("input");
 for(var i = 0, length = inputs.length; i < length ; i++) {
  var input = inputs[i];
  //回车键的keyCode是13
  if(input.type === "text") {
  //按下回车,让下一个文本框获得焦点
  input.onkeydown = function (e) {
   if(e.keyCode === 13) {
   this.nextElementSibling.focus();//focus() 他触发了onfocus事件
   }
  }
  }
 }
 </script>
 </body>

补充:js中的instanceof运算符介绍

判断某个变量是不是某种类型的对象

 var num = 5;
 var arr = [];
 console.log(num instanceof Array);  //false
 console.log(arr instanceof Array);  //true

更多javascript中BOM基础知识总结相关文章请关注PHP中文网!

Statement:
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