[JavaScript基础]学习②⑧--浏览器对象

window

innerWidth和innerHeight属性 获取浏览器窗口的内部宽度和高度

兼容性:IE<=8不支持。

'use strict';
// 可以调整浏览器窗口大小试试:
alert('window inner size: ' + window.innerWidth + ' x ' + window.innerHeight);

outerWidth和outerHeight属性,可以获取浏览器窗口的整个宽高

navigator

navigator.appName 浏览器名称;

navigator.appVersion 浏览器版本;

navigator.language 浏览器设置的语言;

navigator.platform 操作系统类型;

navigator.userAgent 浏览器设定的User-Agent字符串。

'use strict';
alert('appName = ' + navigator.appName + '\n' +
      'appVersion = ' + navigator.appVersion + '\n' +
      'language = ' + navigator.language + '\n' +
      'platform = ' + navigator.platform + '\n' +
      'userAgent = ' + navigator.userAgent);

navigator的信息可以很容易地被用户修改,所以JavaScript读取的值不一定是正确的

var width;
if (getIEVersion(navigator.userAgent) < 9) {
    width = document.body.clientWidth;
} else {
    width = window.innerWidth;
}

改用短路运算符||

var width = window.innerWidth || document.body.clientWidth;

screen

screen.width 屏幕宽度,以像素为单位;

screen.height 屏幕高度,以像素为单位;

screen.colorDepth 返回颜色位数,如8、16、24

'use strict';
alert('Screen size = ' + screen.width + ' x ' + screen.height);

location

一个完整的URL

http://www.example.com:8080/path/index.html?a=1&b=2#TOP
location.href;//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'

加载一个新页面

location.assign()

重新加载当前页面

location.reload()
'use strict';
if (confirm('重新加载当前页' + location.href + '?')) {
    location.reload();
} else {
    location.assign('/discuss'); // 设置一个新的URL地址
}

document

document对象表示当前页面。由于HTML在浏览器中以DOM形式表示为树形结构,document对象就是整个DOM树的根节点。

'use strict';
document.title = '努力学习JavaScript!';//<title>xxx</title>

getElementById() 按ID获得一个DOM节点

getElementsByTagName() 按Tag名称获得一组DOM节点

<dl id="drink-menu" style="border:solid 1px #ccc;padding:6px;">
    <dt>摩卡</dt>
    <dd>热摩卡咖啡</dd>
    <dt>酸奶</dt>
    <dd>北京老酸奶</dd>
    <dt>果汁</dt>
    <dd>鲜榨苹果汁</dd>
</dl>
'use strict';
var i, s, menu, drinks;

menu = document.getElementById('drink-menu');
menu.tagName; // 'DL'

drinks = document.getElementsByTagName('dt');
s = '提供的饮料有:';
for (i=0; i<drinks.length; i++) {
    s = s + drinks[i].innerHTML + ',';
}
alert(s);

cookie

Paste_Image.png

读取到当前页面的Cookie

document.cookie; // 'v=123; remember=true; prefer=zh'
Paste_Image.png

history

history对象保存了浏览器的历史记录
不推荐使用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容