Javascript进阶
浏览器
浏览器对象
// window不仅充当全局变量,且表示浏览器窗口。常用属性
innerWidth/innerHeight // 浏览器内部宽高
outerWidth/outerHeight // 浏览器外部宽高
// navigator表示浏览器信息,d常用属性:
navigator.appName // 浏览器名称;
navigator.appVersion // 浏览器版本;
navigator.language // 浏览器设置的语言;
navigator.platform // 操作系统类型;
navigator.userAgent // 浏览器设定的User-Agent字符串
// screen 表示屏幕信息。常用属性:
screen.width // 屏幕宽度,以像素为单位
screen.height // 屏幕高度,以像素为单位
screen.colorDepth // 返回颜色位数,如8、16、24
// 表示当前页面的URL信息
// e.g. http://www.example.com:8080/path/index.html?a=1&b=2#TOP
location.protocol; // 'http'
location.host; // 'www.example.com'
location.port; // '8080'
location.pathname; // '/path/index.html'
location.search; // '?a=1&b=2'
location.hash; // 'TOP'
// document对象表示当前页面
// 由于HTML在浏览器中以DOM形式表示为树形结构
// document对象就是整个DOM树的根节点
// history
history.back() // 浏览器后退
history.forward() // 浏览器前进
// 强烈建议不y使用
DOM
-
获取DOM
-
通过
document.getElementById()获取一个节点, 通过document.getElementsByTagName()和document.getElementsByClassName()获取一组节点// 返回ID为'test'的节点: var test = document.getElementById('test'); // 先定位ID为'test-table'的节点,再返回其内部所有tr节点: var trs = document.getElementById('test-table').getElementsByTagName('tr'); // 先定位ID为'test-div'的节点,再返回其内部所有class包含red的节点: var reds = document.getElementById('test-div').getElementsByClassName('red'); // 获取节点test下的所有直属子节点: var cs = test.children; // 获取节点test下第一个、最后一个子节点: var first = test.firstElementChild; var last = test.lastElementChild; // 拿到父节点 var father = test.parentElement; -
使用CSS选择器
// 通过querySelector获取ID为q1的节点: var q1 = document.querySelector('#q1'); // 通过querySelectorAll获取q1节点内的符合条件的所有节点: var ps = q1.querySelectorAll('div.highlighted > p');
-
-
更新DOM
-
修改
innerHTML属性,可以在其中添加DOM子树 -
修改
innerText或textContent属性, 会自动对字符串进行HTML编码,保证其中不包含任何标签// 获取...
var p = document.getElementById('p-id'); // 设置文本: p.innerText = ''; // HTML被自动编码,无法设置一个
-