Dom and Bom learning

Table of contents

1. Dom and Bom

1. Understand Dom

2. WebAPIs and APIs

2. Operation elements

1.Abstract

2. Get elements

3. Change element content

4. Form property settings

5. Modify element style

3. Custom attributes

1. Get element attribute value

2. Set element attribute value

3. Remove attribute values

4. Exclusionary Thoughts

5. Key core of Dom

1. Create elements

2. Add elements

3. Delete elements

4. Get elements

6. Events

1. Event composition

2. Execute event steps

3. Common mouse events

4. Add events

5. Delete events

6. Event flow

7. Event object

8. Common properties and methods of event objects

9. The difference between target and this:

10. Event objects prevent default behavior

11. Prevent events from bubbling up

12. Event delegation

13. Mouse event object

14. Keyboard events

15. Keyboard event object

7. BOM part

1. window common events

2. Timer 1 setTimeout / clear timer

3. Timer 2 setTimeInterval / clear timer

8. JS execution mechanism

1. Single-threaded js

2. The emergence of synchronization and asynchronousness in JavaScript

3. Synchronous and asynchronous tasks

4. js execution mechanism

5. Time loop

9. Location object and URL

1. location object

2. URL (Uniform Resource Locator)

3. Properties of location object

4. Methods of location object

5. history object

6. offset attribute

7. The difference between offset and style

8. client attribute

9. scroll attribute

10. Size comparison of three major series

11. Main usage of three series

10. Immediately execute the function

11. Mobile web page special effects

1. touch touch event (touch screen event)

2. Touch event object

3.classList usage

4.transitionEvent object event

5.Plugin ★

6.Framework ★

12. Local storage

1. Local storage—window.sessionStorage

2. Local storage—window.localStorage


1. Dom and Bom

1. Understand Dom

Description: The document object model is a standard programming interface. The content, structure and style of the web page can be changed ( operating page elements ) through the interface provided by Dom.

  • Document: A page is a document
  • Element: All tags on the page are elements
  • Node: All content in the web page is a node (label, attribute, text, comment) node
  • Dom regards all the above contents as objects
  • Dom top-level object is document

Bom: Browser object model, an object structure that can interact with the browser window, eg: pop-up boxes, controlling browser jumps, obtaining resolution, etc. (some objects that the browser window interacts with )

  • Bom consists of a series of related objects, and provides many methods and properties for each object
  • Bom lacks a standard JavaScript syntax. The standardization organization is ECMA, the Dom standardization organization is W3C, and Bom was originally part of the Netscape browser standard.
  • The top-level object of Bom is window

2. WebAPIs and APIs

Web APIs: For the interface provided by the browser, the browser provides interactive effects (Dom and Bom belong to Web APIs)

API: Application programming interface is some predefined functions. API is an interface provided to programmers to help us implement certain functions.

2. Operation elements

1.Abstract

  • this points to the caller of the event function
  • Inline styles have higher weight than inline styles
  • Show properties and methods
console.dir ( )
  • Disable button settings button can no longer be clicked 
this.disabled = 'true';

2. Get elements

Get element Way
getElementById Get element by Id
getElementByTagName by tag name
getElementByClassName by class name
querySelector Selector
querySelectorAll Selector (select all)
document.body

 Get the body element

document.documentElement

 Get html element

3. Change element content

Change element content illustrate
innerText

Does not recognize html tags non-standard

innerHTML  Commonly used W3C standards

4. Form property settings

Form property settings illustrate
 input.value none

5. Modify element style

Modify element style illustrate
element.style Inline style operation (used when the styles to be modified are relatively small)
element.className Class name style operation (you can either overwrite the original class name or retain the original class name)

3. Custom attributes

Definition: Custom properties are now specified to start with data-

1. Get element attribute value

Get element attribute value illustrate
element.property Get built-in property value
element.getAttribute('attribute') Get custom properties
element.dataset.index Get custom properties
element.dataset['index'] Get custom properties

2. Set element attribute value

Set element attribute value illustrate
 element.property='value'  Set built-in property values
 element.setAttribute('attribute','value')  Set custom properties

3. Remove attribute values

Remove attribute value illustrate
removeAttribute('attribute') none

4. Exclusionary Thoughts

Scenario: If there are the same set of elements and we want a certain element to achieve a certain style, we need to use the exclusive idea of ​​​​loops.

Exclusionary Thoughts :

1. Clear the styles of all elements (kill everyone)

2. Set styles for the current element (leave me alone)

3. Be careful not to reverse the order. Kill everyone first and then set yourself up. 

<body>
    <button>按钮1</button>
    <button>按钮2</button>
    <button>按钮3</button>
    <button>按钮4</button>
    <button>按钮5</button>
    <script>
        // 1.获取所有按钮元素
        var btns = document.querySelectorAll('button');
        // btns 得到的是伪数组 里面的每一个元素 btns[i]
        for (var i = 0; i < btns.length; i++) {
            btns[i].onclick = function () {
                // (1) 先去掉所有按钮的背景颜色 干掉所有人
                for (var i = 0; i < btns.length; i++) {
                    btns[i].style.backgroundColor = '';
                }
                // (2) 让当前元素背景颜色变为pink 留下我自己
                this.style.backgroundColor = 'pink';
            }
        }
    </script>
</body>

5. Key core of Dom

1. Create elements

Create elements illustrate
document.write Will cause the page to be redrawn
innerHTML Using array form (not concatenating strings) is highly efficient
createElement

Creating multiple elements is slightly less efficient but the structure is clearer

2. Add elements

Add element illustrate
appendChild

Append after the specified element

insertBefore

Add before the specified element

3. Delete elements

Delete element illustrate
removeChild Delete element

4. Get elements

Get elements using nodes illustrate
parentNode parent node

childNodes

返回所有子节点  (元素节点、文本节点)

children

获取所有的 子元素节点 ★

firstChild

第一个子节点   (元素节点、文本节点)

firstElementChild

返回第一个 子元素节点

nextSibling

下一个兄弟节点  (元素节点、文本节点)

previousSibling

上一个兄弟节点  (元素节点、文本节点)
nextElementSibling

得到下一个兄弟 元素节点 ★

previousElementSibling 得到上一个兄弟 元素节点 ★

六、事件

简单理解:事件就是  触发---响应机制   是可以被js侦测到的行为

1. 事件组成

组成:事件源 事件类型 事件处理程序

  • 事件源:事件被触发的对象 谁 --按钮
  • 事件类型:如何触发 什么时间    eg:点击鼠标onclick、鼠标经过、键盘按下
  • 事件处理程序:通过一个函数赋值的方式 完成

2. 执行事件步骤

  • 获取事件源
  • 注册时间(绑定事件)
  • 添加事件处理程序(采取函数赋值形式)

3. 常见鼠标事件

鼠标事件 触发事件
onclick 鼠标点击触发
onmouseover 鼠标经过触发(鼠标经过自身盒子触发 经过子盒子还会触发);会冒泡
onmouseenter 鼠标经过触发 (只经过自身盒子 会触发);不会冒泡
onmouseout 鼠标离开触发(鼠标离开自身盒子触发 离开子盒子还会触发)
onmouseleave 鼠标离开触发(只离开自身盒子 会触发)
onfocus 获得鼠标焦点触发
onblur 失去鼠标焦点触发

onmousemove

鼠标移动触发
ommouseup 鼠标弹起触发
onmousedown 鼠标按下触发

4. 添加事件

添加事件 说明

Element.onclick = function( ){

         }

传统方式注册事件

Element.addEventListener('click' , function( ){

        })

时间侦听注册事件 函数后边有一个可选参数  默认false

Element.attachEvent('onclick' , function( ) {

       })

ie9以前版本 非标准 尽量不用

5. 删除事件

删除事件 说明
Element.onclick = null ; 传统方式
Element.removeEventLListener('click' , fn) ; 针对 addEventListener

Element.detachEvent('onclick',fn1);

针对 attachEvent

6. 事件流

定义:事件流描述的是 从页面中接收事件的 顺序

事件流的三个阶段 :捕获阶段、当前目标阶段、冒泡阶段

  • js代码中只能执行捕获或者冒泡其中的一个阶段
  • onclick 和 attachEvent (ie) 只能得到冒泡阶段
  • onblur、onfocus、onmouseenter、onmouseleave 没有冒泡阶段
  • 捕获阶段自上而下 document -> html -> body -> father -> son  (addEventListener  第三个参数是 true
  • 冒泡阶段自下而上 son -> father -> body -> html -> document  (addEventListener  第三个参数是 false

7. 事件对象

定义:event就是事件对象 写到我们侦听函数的小括号里边 当形参看 不需要传递实参过去

传统方式

 
        // 1. 传统方式
        var div = document.querySelector('div');
        div.onclick = function (event) {
            console.log(event);
        }
      

addEventListener方式

       var div = document.querySelector('div');
        div.addEventListener('click', function (e) {
            console.log(e);
        })
        // 3. 兼容写法
        div.addEventListener('click', function (e) {
            console.log(window.event);
            e = e || window.event;
        })
  • event对象 代表事件的状态,比如键盘按键的状态、鼠标的位置、鼠标按钮的状态
  • 简单理解:事件发生后,跟事件相关的一系列信息数据的集合 都放到这个对象里边,这个对象就是 事件对象event 它有很多属性和方法
  • 事件对象 只有有了事件才会存在 它是系统给我们自动创建的 不需要我们传递参数
  • 事件对象:是事件的一系列相关数据的集合 跟事件相关的 比如鼠标点击 里面就包含了鼠标的相关信息 鼠标坐标等;如果是键盘事件 里面就包含键盘事件的相关信息 比如 判断用户按下了哪个键
  • 这个事件对象 我们可以自己命名 比如:event 、evt 、e
  • 事件对象也有兼容性问题 ie678 通过 window.event 兼容性的写法  e = e || window.event;

8. 事件对象的常见 属性 和 方法

事件对象 属性 方法 说明
e.target  返回触发事件的对象  标准  ★
e.srcElement 返回触发事件的对象  非标准
e.type 返回事件的类型  比如 click、mouseover、不带on
e.cancelBubble 该属性 阻止冒泡 非标准 ie6~8使用
e.stopPropagation( )  阻止冒泡 标准  ★
e.returnValue 该属性 阻止默认事件(默认行为) 非标准 ie6~8使用 比如不让链接跳转
e.preventDefault( )  该方法 阻止默认事件(默认行为)标准 比如不让链接跳转  ★

9. target 和 this 的区别:

e.target :谁触发了这个事件  指向触发事件的元素 (eg:点击了哪个元素 就返回哪个元素)

this :谁绑定了这个点击事件 就指向谁

10. 事件对象阻止默认行为

让链接不跳转 或者让提交按钮不提交

11. 阻止事件冒泡

阻止事件冒泡 说明

   e.stopPropagation( ); 

propagation 传播
   e.cancelBubble = true;  bubble 泡泡

12. 事件委托

原理:给父节点添加侦听器 利用事件冒泡影响每一个子节点 ★

作用:只操作了一次dom 提高程序性能

  <script>
        var ul = document.querySelector('ul');
        ul.addEventListener('click', function (e) {
            // e.target 可以得到我们点击的对象
            e.target.style.background = 'pink';
        })
    </script>

13. 鼠标事件对象

鼠标事件对象 说明
e.clientX 返回鼠标 相对于浏览器窗口 可视区的X坐标
e.clientY 返回鼠标 相对于浏览器窗口 可视区的Y坐标
e.pageX 返回鼠标 相对于文档页面 的X坐标 (ie9+支持)
e.pageY 返回鼠标 相对于文档页面 的Y坐标 (ie9+支持)
e.screenX 返回鼠标 相对于电脑屏幕的 X坐标
e.screenY 返回鼠标 相对于电脑屏幕的 Y坐标

14. 键盘事件

键盘事件 说明
onkeyup 键盘按键 被松开时 触发
onkeydown 键盘按键 被按下时 触发
onkeypress 键盘按键 被按下时 触发  (不识别功能键 ctrl shift 箭头等)

15. 键盘事件对象

键盘事件对象 说明
keyCode 返回该键的ASCII值

注意:

  • 如果使用addEventListener不需要加 on
  • 三个事件执行顺序:onkeydown -> onkeypress -> onkeyup
  • onkeydown 和  onkeyup 不区分大小写 
  • keypress不识别功能键 但是区分大小写 ;配合keyCode ,返回不同的ASCII值

七、BOM部分

1. window常见事件

window是 浏览器的顶级对象 (Bom的顶级对象是 document)

它是一个全局对象 (定义在全局作用域中的变量、函数 都会变成window对象的属性和方法)

window事件

说明
window.onload

当文档内容 完全加载完成 会触发该事件(包括图像 脚本文件 CSS文件等) ;作用:可以把js代码写到任何地方

window.onload 传统注册事件 只能写一次 若有多个 以最后一个为准;

addEventListener 没有限制

DOMContentLoaded

窗口加载事件,仅当Dom加载完成 不包括样式表、图片、flash (ie9以上支持)  

速度比window.onload快

window.onresize

调整窗口大小加载事件

我们经常利用这个事件 完成响应式布局
window.innerWidth 当前屏幕宽度

2. 定时器1  setTimeout  /  清除定时器

  • 语法规范:window.setTimeout(调用函数,延时时间);

  • 延时时间单位是 毫秒 (可以省略 默认是0)

  • 这个调用函数可以直接写函数 还可以写 函数名 还有一个写法 :'函数名()'

  • 页面中可能有很多定时器 我们经常给定时器加标识符 (名字)

  • setTimeout()函数 我们又成为回调函数callback()  
  • 回调函数:上一件事干完,再回头再调用这个函数
  <script>
        var btn = document.querySelector('button');
        var timer = setTimeout(function () {
            console.log('爆炸了');
        }, 3000);
        // 点击停止定时器
        btn.addEventListener('click', function () {
            clearTimeout(timer);
        })
    </script>

3. 定时器2  setTimeInterval  /  清除定时器

  • 语法规范:window.setInterval(调用函数,延时时间);

  • setInterval 每隔 这个延时时间  就去调用这个回调函数 会调用很多次 重复调用这个函数

  • setTimeout 延时时间到了 就去调用这个回调函数 只调用一次 就结束这个定时器
 <script>
        var begin = document.querySelector('.begin');
        var stop = document.querySelector('.stop');
        var timer = null; // 全局变量 null 是一个空对象
        begin.addEventListener('click', function () {
            timer = setInterval(function () {
                console.log('你好啊');
            }, 1000)
        })
        // 清除setInterval 定时器  clearInterval(参数); 参数:定时器的标识符
        stop.addEventListener('click', function () {
            clearInterval(timer);
        })
    </script>

八、JS执行机制

1. 单线程js

JavaScript 原本是个单线程:同一时间,只能做一件事 (前一个任务结束 才执行后一个任务)

  • 单线程缺点:页面渲染不连贯 页面加载阻塞

2. JavaScript 中同步 和 异步 的出现

  • 同步:前一个任务结束后 再执行后一个任务
  • 异步:做这件事的同时 允许去做别的事情

3. 同步和异步任务

  • 同步任务:在主线程上执行 形成一个执行栈
  • 异步任务:通过 回调函数 实现

异步任务类型:

  • 普通事件:click、resize
  • 资源加载:load、error
  • 定时器:setInterval、setTimeout

4.  js 执行机制

  • 先执行 执行栈中的同步任务
  • 异步任务 (回调函数) 放入任务队列中
  • 一旦执行栈中的所有 同步任务执行完毕,系统就会按次序读取任务队列中异步任务,被读取的异步任务则结束等待状态,进入执行栈 开始执行

5. 时间循环

定义:主线程不断的重复获得任务、执行任务、再获取任务、再执行,这种机制的过程称为event loop

九、location对象 和 URL

1. location 对象

定义:用于获取或设置窗体的URL 并且可以解析URL

2.  URL(统一资源定位符)

protocal://host[:port]/path/[?query]#fragment

http://www.itcast.cn/index.html?name=andy&age=18#link

字符 说明
protocal 通信协议 常用http、ftp、maito等
host 主机(域名)  www.itheima.com 
port 端口号 可选 省略时 使用方案的默认端口号 http默认端口号8080
path 路径 由 零或多个'/'符号隔开的字符串  一般用来表示主机上的一个目录 或 文件地址
query 参数 以键值对的形式 通过&隔开
fragment 片段 #后面内容 常见于链接 锚点

3. location对象的属性

location对象属性 返回值
location.href 获取或者设置 整个URL
location.host 返回主机(域名) www.itheima.com
location.port 返回端口号 如果未写 返回空字符串
location.pathname 返回路径
location.search 返回参数
location.hash 返回片段 #后边内容 常见于链接 锚点

4. location对象的方法

location对象属性 返回值
location.assign()

跟href一样 可以跳转页面(也称为 重定向页面);

可以实现后退功能

location.replace() 替换当前页面 因为不记录历史 所以不能后退页面
location.reload()

重新加载页面 相当于刷新按钮或者 f5 

如果参数为 true 为强制刷新  相当于ctrl + f5

5. history对象

history对象方法 作用
back() 可以后退功能
forward() 前进功能
go(参数)

前进后退功能 参数为1 前进一个页面

参数为 -1 后退一个页面

6. offset属性

  • 获得元素距离 带有定位父元素的位置
  • 获得元素自身的大小(宽度高度)
  • 注意:返回的数值都不带单位

offset常用属性

offset常用属性 作用
element.offsetParent 返回作为该元素 带有定位的父级元素  如果父级都没有定位 则返回body
element.offsetTop 返回元素相对 带有定位父元素 上方的偏移  

没有父亲或者父亲没有定位 则以 body 为准

element.offsetLeft

返回元素相对 带有定位父元素 左边框的偏移

没有父亲或者父亲没有定位 则以 body 为准

element.offsetWidth 返回自身包括padding、边框、盒子的宽度,返回数值不带单位
element.offsetHeight 返回自身包括padding、边框、盒子的高度,返回数值不带单位

7. offset 与 style 的区别

offset

  • 可以得到任意样式表中的样式值
  • 获得的数值没有单位
  • offsetWidth包含padding+border+width
  • offsetWidth属性是只读属性 只能获取不能赋值
  • 想要获取元素大小位置 offset更合适

style

  • 只能得到行内样式表中的样式值
  • style.width 获得的是带有单位的字符串
  • style.width 获得的值不包含padding 和 border
  • style.width 是可读写属性 可以获取也可以赋值
  • 想要给元素更改值 style更方便

8. client属性

client 翻译过来是 客户端,这里是获取元素可视区的相关信息

client属性 作用
element.clientTop 返回元素 上边框大小
element.clientLeft 返回元素 左边框大小
element.clientWidth 返回自身包括padding、盒子的宽度,不含边框,返回数值不带单位
element.clientHeight 返回自身包括padding、盒子的高度,不含边框,返回数值不带单位

9. scroll属性

scroll属性 作用
element.scrollTop 返回 被卷去的上侧距离,返回数值不带单位
element.scrollLeft 返回 被卷去的左侧距离,返回数值不带单位
element.scrollWidth 返回自身实际的宽度,不含边框,返回数值不带单位
element.scrollHeight 返回自身实际的高度,不含边框,返回数值不带单位

10. 三大系列大小对比

三大系列大小对比 作用
element.offsetWidth 返回自身包括padding、边框、盒子的宽度,返回数值不带单位
element.clientWidth 返回自身包括padding、盒子的高度,不含边框,返回数值不带单位
element.scrollWidth 返回自身实际的宽度,不含边框,返回数值不带单位

11. 三大系列主要用法

  • offset系列 常用于 获取元素位置 offsetTop 、offsetLeft
  • client系列 常用于 获取元素大小 clientWidth、clientHeight
  • scroll系列 常用于 获取滚动距离 scrollTop、scrollLeft
  • 注意:页面滚动距离通过 window.pageYOffset 获得 ★★

十、立即执行函数

立即执行函数:不需要调用,立马能够自己执行的函数  (可以传递参数进来)

第二个小括号可以看做是 调用函数   ()()   (  ())  

作用:独立创建了一个作用域, 里边的所有变量都是局部变量 不会有命名冲突的情况

 // 1. (function(){})()
        (function (a, b) {
            console.log(a + b); // 3
        })(1, 2);

 // 2. (function(){}()) 
        (function (c, d) {
            console.log(c * d); // 35
        }(5, 7))

十一、移动端网页特效

1. touch触摸事件(触屏事件)

触屏touch事件 说明
touchstart 手指触摸到一个 DOM元素时触发
touchmove 手指在一个DOM 元素上滑动时触发
touchend 手指从一个DOM元素上移开时触发

2. 触摸事件对象

触摸列表 说明
touches 正在触摸屏幕的所有手指的一个列表
targetTouches 正在触摸当前DOM元素上的手指的一个列表 ★
changedTouches 手指状态发生了改变的列表 从无到有 从有到无

3.classList 用法

classList 用法 说明

classList [ index ]

返回元素的类名

classList.add

添加类名

classList.remove

删除类名

classList.toggle

切换类 (开关灯效果)

原来有这个类名     就删除

原来没有这个类名  就添加

4.transitionEvent对象 事件

事件 描述
transitionend 过渡动画 结束后 触发

5.插件 ★

插件:js插件就是 js文件,为了解决某个问题而存在(小而专一,某个功能的解决方案)

(1)前端常用 移动端插件:swiper、superslide、iscroll、fastclick 等

  • fastclick 插件 解决移动端click事件 300s延迟问题( 移动端屏幕双击缩放页面引起的)
  • 禁用缩放:<meta name = "viewport" content = "user-scalable = no">
  • superslide 插件:http://www.superslide2.com/
  • iscroll 插件:https://github.com/cubiq/iscroll

(2)插件使用总结

  • 确认插件 实现功能
  • 去官网 查看使用说明
  • 下载插件
  • 打开 demo 实例文件 查看需要引入的相关文件,并且引入
  • 复制 demo 实例文件中的结构html、样式css以及js代码

6.框架 ★

框架:基于自身特点,向用户提供的一套较为完整的解决方案(大而全,一整套解决方案)

(1)前端常用框架:Bootstrap、Vue、Angular、React 等(支持PC端、移动端开发)

(2)Bootstrap 使用步骤:

  • 引入相关 js 文件
  • 复制 HTML 文件
  • 修改对应样式
  • 修改相应 JS 参数
  • 引入Bootstrap.js 时,必须先引入jQuery.js

十二、本地存储

1. 本地存储—window.sessionStorage

  • 生命周期为 关闭浏览器窗口
  • 在同一个窗口(页面)下数据可以共享
  • 以键值对的形式存储使用
sessionStorage 说明
setItem(key,value) 存储数据
getItem(key) 获取数据
removeItem(key) 删除数据
clear() 删除所有数据

2. 本地存储—window.localStorage

  • 生命周期永久生效 除非手动删除 否则关闭页面也会存在
  • 同一浏览器可以共享
  • 以键值对的形式存储使用
localStorage 说明
setItem(key,value) 存储数据
getItem(key) 获取数据
removeItem(key) 删除数据
clear() 删除所有数据

本地存储 只能存储-->字符串的数据格式

  • 保存到本地存储 数据:数组转换字符串  JSON.stringify()  
  • 获取本地存储的 数据:字符串转换对象 JSON.parse()  

Guess you like

Origin blog.csdn.net/angel_791/article/details/125467273