一、BOM
Window对象
概念:
所有全局js对象(String、Number、Boolen、Array、Object、Date、Math、Regexp)
全局js函数,
全局js变量,
document对象都是windows对象成员
window.document.getElementById();
//等同于
document.getElementById();
window.scrollTo(x,y)//滚动到距离文档窗口的水平、垂直距离
//等同于
window.scrollTo({
left:水平距离
top:垂直距离
behavior:'smooth/instant(默认)'
})
浏览器窗口尺寸大小(可视区域)
//window.innerHeight - 浏览器窗口的内高度(以像素计)
//window.innerWidth - 浏览器窗口的内宽度(以像素计)
//兼容
var with = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
Screen对象
概念:用户屏幕(电脑)信息
screen.width
screen.height
screen.availWidth
screen.availHeight
screen.colorDepth
screen.pixelDepth
Location对象
概念:获取当前页面地址URL并把浏览器重定向到新页面
//属性
window.location.href → 'https://www.jianshu.com/search?q=JS#comments'
.origin → 'https://www.jianshu.com'
.protocol → 'https:'
.host → 'www.jianshu.com'包含端口号
.hostname → 'www.jianshu.com'
.port → ''
.pathname → '/search/'
.search → '?q=JS'
.hash → '#comments'
//方法
window.location.assign('url')
.replace('url')
.reload()
.toString()
//window.location.href与window.location.replace区别
window.location.replace(url) //替换掉当前浏览记录
.href(url)
History对象
概念:浏览器的路由历史
history.back() // 等同于在浏览器点击后退按钮 history.go(-1)
history.forward() // 等同于在浏览器中点击前进按钮. history.go(1)
history.go() //history.go(0)当前页面刷新
//HTML5新增
history.pushState(state, title, url) //添加浏览历史记录 不会刷新页面,只导致地址栏发生变化
history.replaceState(state, title, url) //修改浏览历史记录 替换掉当前的
Navigator对象
概念:有关浏览器的信息
navigator.cookieEnabled 浏览器cookie是否禁用
navigator.appName 浏览器应用程序名称
navigator.appCodeName 浏览器应用程序代码名称
弹出框
警告框
window.alert('text')
确认框:点击确定返回true,点击取消返回false
window.confirm('text')
提示框:点击确定返回输入框里面的值,点击取消返回Null
window.prompt('text','defaultValue')
Timing事件
setTimeout(function, milliseconds) clearTimeout()
setInterval(function, milliseconds) clearInterval()
Cookie\localStorage\sessionStorage
//设置
cookie.setItem(key, content)
//获取
cookie.getItem(key)
//删除
cookie.removeItem(key)
编码/解码
encodeURI与encodeURIComponent区别
//编码
encodeURIComponent()
//解码
decodeURIComponent()
二、js中的DOM事件
- 鼠标事件
- 键盘事件
- 表单事件
- 触摸事件
//window的resize事件
<style>
html,body{
height: 100%;
padding: 0;
margin: 0;
}
.box {
display: flex;
height: 100%;
}
.left {
width: 500px;
height: 100%;
background-color: yellowgreen;
}
.right {
flex: 1;
}
</style>
<body>
<div class="box">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
<script>
var Left = document.getElementsByClassName('left')[0];
window.addEventListener('resize',() => {
if(window.innerWidth > 800){
Left.style.width = '500px';
} else {
Left.style.width = '200px';
}
})
</script>