day7_JavaScript(2)
2018-08-23 本文已影响0人
KingJX
-
1、添加事件
添加事件方式
var odiv = document.getElementById('div')
odiv.onclick = function () {}
-
显示隐藏图片
操作div的display属性,在block和none之间切换即可 -
this使用
在匿名函数中的this就是当前对象
在onclick=demo(this) 就是当前节点
修改内容
this.innerHTML = 'xxx' -
切换背景色
表单内容控制
<script>
var odiv = document.getElementById('bai')
odiv.onclick = function () {
// 先获取div的背景色
color = this.style.backgroundColor
if (color == 'red') {
this.style.backgroundColor = 'yellow'
} else {
this.style.backgroundColor = 'red'
}
}
-
2、onload函数
window的事件,windows.onload = function () {} 是在整个文档加载完毕之后执行,但是自己写的onclick的点击函数不能写到onload里面,因为内部函数只能在内部使用,不能再外部使用
-
3、定时器
定时器:分为两种,一种是周期性定时器,一种是一次性定时器
周期性:每隔5s执行一次函数
一次性:几秒之后执行一次函数,执行完毕定时器结束
var timer = setTimeout(fn, 5000)
5000ms之后执行fn一次。然后结束
销毁定时器 clearTimeout(timer)
计数器
图片消失 -
4、获取非行内样式
IE浏览器获取非行内样式方式
obj.currentStyle['name']
火狐和谷歌获取方式
getComputedStyle(odiv, null)['width']
获取非行内样式的兼容性写法
function getStyle(obj, name) {
return obj.currentStyle ? obj.currentStyle[name] : getComputedStyle(obj, null)[name]
}
-
5、BOM操作
window.setTimeout,window.setInterval
window.alert\window.confirm
window.open
window.history(back、go)
history.go(1) 去往前一个网址
history.go(2) 去往后一个网址
history.back() 倒退一个网址
location
href : 读取得到当前的url,设置跳转到指定的url
reload() : 刷新整个页面 -
6、DOM操作
children
parentNode
firstElementChild
lastElementChild
previousElementSibling
nextElementSiblingfirstChild
lastChild
previousSibling
nextSiblingtagName
createElement
removeChild
appendChild
insertBeforesetAttribute getAttribute
-
7、select下拉框和oninput事件
onchange : 事件,用户点击下拉框触发
selectedIndex : 用户点击的option的下标,下标从0开始
options : osel.options 可以得到所有的option对象,这是一个数组input框的oninput事件,只要内容改变,就会触发