Home > Web Front-end > Front-end Q&A > what is javascript bom

what is javascript bom

青灯夜游
Release: 2023-01-06 11:17:06
Original
5171 people have browsed it

In JavaScript, BOM refers to the Browser Object Model (Browser Object Model), which provides objects that interact with the browser window independently of the content. It is mainly used to manage the interaction between windows. Communication, its core object is window.

what is javascript bom

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. What is BOM

  • BOM (Browser Object Model) is the browser object model.

  • BOM provides objects that interact with the browser window independently of content;

  • Since BOM is mainly used to manage windows and windows communication between each other, so 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. 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, the location object and history object that can be used for navigation, the navigator and screen objects that can obtain browser, operating system, and user screen information, and the document can be used as the entrance to access and manage HTML documents. 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. .

BOM structure diagram

##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. You can omit the window when calling.

Example:

Open the window

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

Close the window:

window.close();
Copy after login

4. BOM fragmentary knowledge (window object)

1. Timer

Delayed execution

setTimeout( [string | function] code, interval);
clearTimeout([number] intervalId);
Copy after login
<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>
Copy after login

Timing execution

var timerId = setInterval(code, interval);
clearInterval(timerId);     //清除定时器
Copy after login

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>
Copy after login

2.offset series method

##offsetLeft and offsetTopoffsetLeft Form #1, to the left/top of the nearest (positioned) parent elementThe difference between offsetLeft and style.left1, style.left can only get inline styles

offsetWidth and offsetHeight

The composition of offsetHeight

offsetHeight = height padding border

offsetWidth is the same

##The difference between offsetHeight and 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 (without unit)

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

So: demo.style.height gets the real height/width of an element, and uses .style.height to set it Height/Width

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

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

2,offsetLeft只读,style.left可读可写

3,offsetLeft是数值,style.left是字符串并且有单位px

4,如果没有定位,style.left获取的数值可能是无效的

5,最大的区别:offsetLeft以border左上角为基准, style.left以margin左上角为基准

offsetParent

构成

1. 返回该对象距离最近的带有定位的父级元素

2. 如果当前元素的所有父级元素都没有定位(position为absolute或relative),那么offsetParent为body

3. offsetLeft获取的就是相对于offsetParent的距离

与parentNode的区别

parentNode始终指向的是当前元素的最近的父元素,无论定位与否

offset示意图

3.scroll系列方法

scrollHeight和scrollWidth对象内部的实际内容的高度/宽度(不包括border)
scrollTop和scrollLeft被卷去部分的顶部/左侧 到 可视区域 顶部/左侧 的距离
onscroll事件滚动条滚动触发的事件
页面滚动坐标var scrollTop = window.pageYoffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

scroll示意图

4.client系列

clientX和clientY 获取鼠标在可视区域的位置 clientX = width + padding,clientY = height + padding

clientLeft 边框的宽度,若有滚动条的话,包括滚动条

client示意图

例: 获得页面可视区域的大小

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

5.事件参数e

当事件发生的时候,系统会自动的给事件处理函数传递一个参数,会提供事件相关的一些数据,事件参数e浏览器的兼容性检测: e = e || window.event

e.pageX和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>
Copy after login

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

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

阻止默认行为的执行

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

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

<body>
    <a href="http://www.baidu.com" 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>
Copy after login

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" id="link">百度</a>
<script>
//    var regularExpression =  new RegExp("\\d");     //第一种写法
    var regularExpression = /\d/;     //第二种写法
    var str = "adfj23dald";
    console.log(regularExpression.test(str));     //test就是匹配方法,结果是true
</script>
</body>
Copy after login

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));
Copy after login

8.3 正则之提取

例:找数字

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

8.4 正则之替换

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

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

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);
Copy after login

9.键盘事件对象

方法

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>
Copy after login

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

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

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

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of what is javascript bom. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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