事件的三种加载方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#div01{
width: 300px;
height: 330px;
background-color: #01AAED;
}
</style>
</head>
<body>
<div id="div01" ></div>
<div id="div02" onclick="divClick(this);" ></div>
<script src="../jquery-3.3.1.min.js"></script>
<script>
var div01 = document.getElementById('div01');
// 第一种写法
// div01.onclick = function () {
// alert(222);
// }
第二种写法
function divClick(obj) {
obj.style.background = 'yellow';
}
// 第三种写的
div01.addEventListener('click',function () {
this.style.background = 'yellow';
})
</script>
</body>
</html>
事件
event | description |
---|---|
onclick | 鼠标点击 |
ondblclick | 鼠标双击 |
oncontextmenu | 鼠标右击 |
onmouseover | 鼠标移入 |
onmouseout | 鼠标移出 |
onmousemove | 鼠标移动 |
onmousedown | 鼠标按下 |
onmouseup | 鼠标抬起 |
实例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
.div01{
width: 300px;
height: 300px;
background-color: #5bc0de;
}
</style>
</head>
<body>
<div class="div01">
我事件测试的div
</div>
<script src="../jquery-3.3.1.min.js"></script>
<script>
var div = document.getElementsByClassName('div01');
console.log(div);
/*
div[0].onclick = function () {
console.log('我被点击了.........');
}
div[0].ondblclick = function () {
console.log('我被双击了.........');
}
div[0].oncontextmenu = function () {
console.log('我被右击了..........');
}
div[0].onmouseover = function () {
console.log('我是鼠标移入........');
}
div[0].onmouseout = function () {
console.log('我是鼠标移出..........');
}
div[0].onmousemove = function () {
console.log('我是鼠标移动.......');
}
div[0].onmousedown = function () {
console.log('我被按下了.........')
}
div[0].onmouseup = function () {
console.log('我被抬起了...........')
}
*/
div[0].onmousemove = function (e) {
// js中会自动将事件对象赋值给形参 e
console.log(e);
// e.vlientX : 鼠标距离屏幕左上角的水平距离
// e.pageX : 鼠标距离文档左上角的值
console.log(e.clientX,e.clientY,e.pageX,e.pageY);
// offsetWith = border + padding + width
console.log(this.offsetWidth,this.offsetHeight);
// offsetTop : 参考对象是里他最近的参考对象如果没有 默认是 body
console.log(this.offsetTop,this.offsetLeft);
}
</script>
</body>
</html>
网友评论