键盘按下的时候触发 onkeydown
连续敲击的时候触发 onkeypress
键盘抬起的时候触发 onkeyup
顺序 onkeydown > onkeypress > onkeyup
在输入框中输入 字符 按下回车的时候 把输入的字 alert出来
<body>
用户名:<input type="text" id="t">
<script>
let t = document.getElementById('t');
t.onkeydown = function (e){
/* 兼容写法 */
let eobj = e||event;
/* 事件源对象 */
console.log(eobj);
if(eobj.keyCode == 13){
// alert(this.value)
alert(eobj.target.value)
}
}
</script>
</body>
默认事件
两种禁用默认事件方式
return false会阻止下面代码的执行 方法已经结束了
e.preventDefault()不会阻止下面代码执行
鼠标右击 禁止出现默认的菜单 显示一个自己的菜单 菜单A 菜单B 菜单C 出现的位置就是 鼠标的位置
<body>
<div id="div1">
</div>
<script>
let div1 = document.getElementById('div1')
div1.onmousedown = function (e) {
console.log(div1.offsetLeft);
let areaW = e.clientX - div1.offsetLeft
let areaH = e.clientY - div1.offsetTop
document.onmousemove = function (ee) {
div1.style.left = (ee.clientX - areaW) + 'px'
div1.style.top = (ee.clientY - areaH) + 'px'
}
}
div1.onmouseup = function () {
document.onmousemove = null;
}
</script>
</body>
鼠标点击位置 鼠标在文档的X轴的位置 console.log(e.clientX);
鼠标在文档的Y轴的位置 console.log(e.clientY);
拖拽事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div1{
width: 150px;
height: 150px;
background-color: blueviolet;
position: absolute;
left:100px;
top:0px;
}
</style>
</head>
<body>
<div id="div1"></div>
<script>
let div1 = document.getElementById('div1')
div1.onmousedown = function (e){
/* 按下的时候 获取点的位置 到盒子边界距离 */
let areaX = e.clientX - div1.offsetLeft;
let areaY = e.clientY - div1.offsetTop;
document.onmousemove = function (e){
/* 移动的时候获取的client的动态距离 - 盒子内点的到边缘的固定距离 */
/* 最后获得的 就是 盒子到文档的距离 */
div1.style.left = e.clientX - areaX + 'px'
div1.style.top = e.clientY - areaY + 'px'
}
}
div1.onmouseup = function (){
document.onmousemove = null;
}
</script>
</body>
</html>