事件对象
var box = document.querySelector('.box');
box.onmouseover = function(event){
// console.log(event);
console.log(window.event.type);
var e = event || window.event;
}
- 阻止冒泡
var big = document.querySelector('.big')
var middle = document.querySelector('.middle')
var small = document.querySelector('.small')
big.onclick = function(){
console.log("大");
}
middle.onclick = function(){
console.log("中");
}
small.onclick = function(e){
var e = e || window.event;
console.log("小");
// 需要事件对象来阻止冒泡 - e.stopPropagation()
// e.stopPropagation()
// 低版本ie中
// e.cancelBubble = true
兼容的阻止冒泡
if(e.stopPropagation){
e.stopPropagation()
}else{
e.cancelBubble = true
}
}
- 获取鼠标的按键信息
var box = document.querySelector('.box')
box.onmousedown = function(e){
var e = e || window.event;
console.log(e);
console.log(e.button);
}
- 键盘码
window.onkeydown = function(e){
// 获取键盘码
var e = e || window.event;
// 键盘码 - e.keyCode
// 键盘码在低版本火狐中不兼容
// 兼容 写法
var keycode = e.keyCode || e.which;
console.log(keycode);
// 如果要判断是否按下的是a键
// 将键盘码获取到,转成字符
var s = String.fromCharCode(keycode)
// console.log(s);
// 转小写
s = s.toLowerCase()
console.log(s);
- 鼠标坐标点
var box = document.querySelector('.box')
document.onclick = function(e){
var e = e || window.event;
console.log(e);
// e.offsetX e.offsetY - 鼠标在当前事件源上的位置
console.log(e.offsetX,e.offsetY);
// e.clientX e.clinetY - 鼠标在浏览器中的位置
console.log(e.clientX,e.clientY);
// e.pageX e.pageY - 鼠标在整个页面中的绝对距离 - 包含了滚动过的距离
console.log(e.pageX,e.pageY);
console.log(document.documentElement.scrollTop);
}
拖拽div
var box = document.querySelector('.box')
box.onmousedown = function(e){
var e = e || window.event;
var x1 = e.offsetX;
var y1 = e.offsetY;
document.onmousemove = function(e){
var e1 = e || window.event;
var x2 = e1.pageX;
var y2 = e1.pageY;
var left = x2 - x1;
var top = y2 - y1;
box.style.left = left + "px"
box.style.top = top + "px"
}
}
window.onmouseup = function(){
document.onmousemove = null
}
- 阻止默认行为
1.事件对象
if(e.preventDefault){
e.preventDefault()
}else{
e.returnValue = false
}
2.将链接改成 javascipt:; javascript:void(0);
3.在事件函数的最下面添加:return false
- 事件委托
var lis = document.querySelectorAll('li')
for(var i=0;i<lis.length;i++){
lis[i].onclick = function(){
console.log(this.innerText);
}
}
var ul = document.querySelector('ul')
ul.onclick = function(e){
var e = e || window.event;
// e.target - 当前点击的最精准的子标签
var target = e.target || e.srcElement;
console.log(target.innerText);
}