Skip to content

Dom&Bom

Dom

Document Object Model文档对象模型,是一种树形结构

获取Dom

javascript
/**
 * 获取Dom
 */

console.log('----getElementById----');
let byId = document.getElementById('list');
console.log(byId);

console.log('----getElementsByTagName----');
let byTag = document.getElementsByTagName('ul');
console.log(byTag[0]);

console.log('----getElementsByClassName----');
let byClass = document.getElementsByClassName('list');
console.log(byClass[0]);

console.log('----querySelectorAll----');
let bySelector = document.querySelectorAll('.list');
console.log(bySelector[0]);

修改样式

javascript
/**
 * 修改样式 两者都可能引起dom重新渲染
 */

// property方式,修改对象的属性,不会体现到html结构中
byId.style.fontSize = '32px';

// attribute方式,修改html属性,会改变html结构
byId.setAttribute('style', 'color: #444');

操作Dom

操作Dom比较耗时和耗资源,避免频繁的操作Dom
优化:

  1. 将查询结果缓存下来
  2. 将多次操作合并成一次来完成
javascript
/**
 * 操作Dom
 * @type {Element}
 */
// 避免频繁操作Dom,
let $list = document.querySelectorAll('.list')[0];

// 创建一个文档片段,此时并没有插入到Dom结构当中
let virDom = document.createDocumentFragment();

for (let i = 0; i < 10; i++) {
    let $li = document.createElement('li');
    $li.innerHTML = `This is ${i} item`;
    // 先插入到文档片段当中
    virDom.appendChild($li);
}

// 一次完成
$list.appendChild(virDom);

Bom

Browser Object Model浏览器对象模型

包含,
location、screen、navigator、history

location

提供文档有关信息与导航功能

assign: ƒ assign()
hash: ""
host: "localhost:63342"
hostname: "localhost"
href: "http://localhost:63342/daily-code/javascript/js-web-api/bom.html?_ijt=mi6ohh0fq2vcn0nrpjmpqe1b0a&_ij_reload=RELOAD_ON_SAVE"
origin: "http://localhost:63342"
pathname: "/daily-code/javascript/js-web-api/bom.html"
port: "63342"
protocol: "http:"
reload: ƒ reload()
replace: ƒ replace()
search: "?size=10&page=1"

将url参数,转换为对象的实现

javascript
let getParams = function () {
    // 将参数转换为键值对形式
    let search = location.search;
    let searchList = [];
    let params = {};
    if (search && search.length > 0) {
        searchList = search.substring(1).split('&');
        searchList.map(item => {
            let query = item.split('=');
            params[query[0]] = query[1];
        });
    }
    console.log(params);
    return params;
}
getParams();

浏览器信息,获取浏览器用户代理字符串,使用 navigator.userAgent

iOS设备检测

javascript
/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) // i,不区分大小写

screen

浏览器外部显示器信息,基本用不到

availHeight: 1127
availLeft: -2048
availTop: -113
availWidth: 2048
colorDepth: 24
height: 1152
orientation: ScreenOrientation {angle: 0, type: 'landscape-primary', onchange: null}
pixelDepth: 24
width: 2048

history

用户上网的历史记录,可以操作前进或者后退跳转到任意页面

javascript
history.length // History.length是一个只读属性,返回当前session中的history个数,包含当前页面在内
history.back(); // 后退
history.forward(); // 前进
history.go(3); // 前进
history.go(-3); // 后退
history.pushState(state, title[, url]) // 向当前浏览器会话的历史堆栈中添加一个状态
history.replaceState(state, title[, url]); // 修改当前历史记录实体