js分享10-事件(小白必看)

什么是 事件

  • 一个事件的组成

    • 触发谁的事件: 事件源

    • 触发什么事件: 事件类型

    • 触发后做什么: 事件处理函数

var box = document.querySelector("div");
box.onclick = function () {};
/**
 * 触发谁的事件 ---> oDiv ---> 事件源就是 box
 * 触发什么事件 ---> onclick ---> 事件类型就是 click
 * 触发后做什么 ---> function () {} ---> 事件的处理函数
 */
var box = document.querySelector("div");
box.onclick = function () {
    console.log("你点击了 div");
};
  • 当我们点击 div 的时候, 就会执行事件处理函数内部的代码

  • 每点击一次, 就会执行一次事件处理函数

事件的绑定方式

  • 我们现在给一个注册事件都是使用 onXXX 的方式

  • 但是这种方式不是很好, 只能给一个元素注册一个事件, 如果写了第二个, 那么第一个会被覆盖

box.onclick = function () {
    console.log("第一个事件");
};
box.onclick = function () {
    console.log("第二个事件");
};
  • 我们这种绑定方式, 只会执行第二个, 第一个就没了

  • 如果想要两个都存在, 我们可以使用 事件监听的方式 去给元素绑定事件

  • 使用 addEventListener 的方式添加

    • 在 IE 中要使用 attachEvent

事件监听

addEventListener (非 IE7 8 下使用)
  • 语法: 元素.addEventListener('事件类型', 事件处理函数, 冒泡还是捕获)

oDiv.addEventListener(
    "click",
    function () {
        console.log("我是第一个事件");
    },
    false
);
oDiv.addEventListener(
    "click",
    function () {
        console.log("我是第二个事件");
    },
    false
);
  • 点击 div 时, 两个函数都会执行, 并且会按照你注册的顺序执行

  • 先打印 我是第一个事件, 然后打印 我是第二个事件

  • 注意: 事件类型不要写 on, 点击事件就是 click, 不是 onclick

attachEvent (IE 7 8 下 使用)
  • 语法: 元素.attachEvent('事件类型', 事件处理函数)

oDiv.attachEvent("click", function () {
    console.log("我是第一个事件");
});
oDiv.attachEvent("click", function () {
    console.log("我是第二个事件");
});
  • 点击 div 时, 两个函数都会执行, 并且会按照你注册的顺序倒叙执行

  • 先打印 我是第二个事件, 然后打印 我是第一个事件

  • 注意: 事件类型需要要写 on, 点击事件就是 onclick

两个方式的区别
  • 注册事件的时候事件类型参数的书写

    • addEventListener: 需要写 on

    • attachEvent: 不需要写 on

  • 参数个数

    • addEventListener: 一般是三个常用参数

    • attachEvent: 两个参数

  • 执行顺序

    • addEventListener: 顺序注册, 顺序执行

    • attachEvent: 顺序注册, 倒叙执行

  • 适用浏览器

    • addEventListener: 非 IE 7 8 的浏览器

    • attachEvent: IE 7 8 浏览器

事件监听案例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        ul,
        ol {
            list-style: none;
        }

        .header {
            width: 600px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            background-color: rgb(140, 213, 237);
            display: flex;
        }

        .header li {
            width: 200px;
        }

        .content {
            width: 600px;
            height: 400px;
            line-height: 400px;
            text-align: center;
        }

        .header .active {
            background-image:linear-gradient(rgb(30, 209, 27),rgb(133, 233, 156))
        }

        .content li {
            display: none;
            font-size: 50px;
        }

        .content .active {
            display: block;
            background-image:linear-gradient(lightblue,pink)
        }
    </style>
</head>

<body>
    <ul class="header">
        <li class="active">header_1</li>
        <li>header_2</li>
        <li>header_3</li>
    </ul>
    <ol class="content">
        <li class="active">content_1</li>
        <li>content_2</li>
        <li>content_3</li>
    </ol>
</body>
<script>
    // 获取标签
    var header = document.querySelector('.header')
    var content = document.querySelector('.content')
    var list = document.querySelectorAll('.header>li')
    var list_sec = document.querySelectorAll('.content>li')
    // 添加事件
    for (let i = 0; i < list.length; i++) {
        list[i].addEventListener('click', function () {
            // 取消所有li类名
            for (var j = 0; j < list.length; j++) {
                list[j].className = ''
                list_sec[j].className = ''
            }
            // 给点击的li添加类名
            list[i].className = 'active'
            list_sec[i].className = 'active'
        })
    }
</script>

</html>

常见的事件 (了解)

  • 事件分类

    • 浏览器事件

    • 鼠标事件

    • 键盘事件

    • 表单事件

    • 触摸事件

浏览器事件
  • load: 页面全部资源加载完毕

  • scroll: 浏览器滚动的时候触发

  • ...

鼠标事件
  • click: 点击事件
    box.onclick = function (){ console.log('单击'); }

  • dblclick: 双击事件
    box.ondblclick = function (){console.log('双击');}

  • contextmenu: 右键事件
    box.oncontextmenu = function(){console.log('右键');}

  • mousedown: 鼠标左键按下事件
    box.oncontextmenu = function(){console.log('左键按下');}

  • mouseup: 鼠标左键抬起事件
    box.onmouseup = function(){console.log('左键抬起');}

  • mousemove: 鼠标移动
    box.onmousemove = function(){console.log('鼠标移动');}

  • mouseover: 鼠标移入事件
    box.onmouseover = function(){console.log('鼠标移入');}

  • mouseout: 鼠标移出事件
    box.onmouseout = function(){console.log('鼠标移出');}

  • mouseenter: 鼠标移入事件
    box.onmouseenter = function(){console.log('鼠标移入');}

  • mouseleave: 鼠标移出事件
    box.onmouseleave = function(){console.log('鼠标移出');}

  • ...

键盘事件
  • keyup: 键盘抬起事件
    inp.onkeyup = function(){console.log('键盘抬起');}

  • keydown: 键盘按下事件
    inp.onkeydown = function(){console.log('键盘按下');}

  • keypress: 键盘按下在抬起事件
    inp.onkeypress = function(){console.log('键盘按下再抬起');}

  • ...

表单事件
  • focus: 输入框获取焦点
    inp.onfocus = function(){console.log('获取');}

  • blur: 输入框失去焦点
    inp.onblur = function(){console.log('失去');}

  • change: 表单内容改变事件
    inp.onchange = function(){console.log('改变');}

  • input: 表单内容输入事件
    inp.oninput = function(){console.log('输入');}

  • ...

触摸事件
  • touchstart: 触摸开始事件
    box.ontouchstart = function(){console.log('触摸开始');}

  • touchend: 触摸结束事件
    box.ontouchend = function(){console.log('触摸结束');}

  • touchmove: 触摸移动事件
    box.ontouchmove = function(){onsole.log('触摸移动');}

  • ...

事件对象

  • 什么是事件对象

    • 当触发一个事件以后, 对该事件的一些描述信息

    • 比如: 点击的位置坐标是什么, 触发键盘事件时按的那个按钮

  • 每一个事件都会有一个对象的对象来描述这些信息, 我们就把这个对象叫做 事件对象

  • 浏览器给了我们一个 黑盒子, 叫做 window.event, 就是对事件信息的所有描述

    • 比如点击事件, 我们可以通过 event 对象知道我们点击了那个位置

oDiv.onclick = function () {
    console.log(window.event.X轴坐标点信息);
    console.log(window.event.Y轴坐标点信息);
};
  • 但这东西有兼容性问题, 在低版本IE里很好用, 但是在高版本IE和Chrome 里不好使了

  • 所以我们需要换一个方式来获取, 就是在每一个事件处理函数的形参位置, 默认第一个就是 事件对象

oDiv.onclick = function (e) {
    console.log(e.X轴坐标点信息);
    console.log(e.Y轴坐标点信息);
};
  • 综上所述, 我们以后在每一个事件里, 都采用兼容写法

oDiv.onclick = function (e) {
    e = e || window.event;
    console.log(e.X轴坐标点信息);
    console.log(e.Y轴坐标点信息);
};

点击事件的光标点获取

  • 我们点击事件的坐标点都不是一堆, 所以要有一个相对的坐标系

  • 例如:

    • 相对于事件源(就是我们点击的那个元素)

    • 相对于页面

    • 相对于浏览器窗口

  • 因为这些都不一样, 所以我们获取的方式也不一样

相对于事件源
  • offsetX 和 offsetY

  • 相对于我们点击的元素的边框内测开始计算

* {
	margin: 0;
	padding: 0;
}
div {
	width: 300px;
	height: 300px;
	padding: 20px;
	border: 10px solid #333;
	margin: 20px 0 0 30px;
}

<div></div>

var oDiv = document.querySelector('div')

// 注册点击事件
oDiv.onclick = function (e) {
	// 事件对象兼容写法
	e = e || window.event

	console.log(e.offsetX)
	console.log(e.offsetY)
}
相对于浏览器窗口你点击的坐标点
  • clientX 和 clientY

  • 相对于浏览器窗口来计算的, 不管你页面滚动到什么情况, 都是根据窗口来计算坐标

* {
	margin: 0;
	padding: 0;
}
body {
	width: 2000px;
	height: 2000px;
}
div {
	width: 300px;
	height: 300px;
	padding: 20px;
	border: 10px solid #333;
	margin: 20px 0 0 30px;
}

<div></div>

var oDiv = document.querySelector('div')

// 注册点击事件
oDiv.onclick = function (e) {
	// 事件对象兼容写法
	e = e || window.event

	console.log(e.clientX)
	console.log(e.clientY)
}
相对于页面你点击的坐标点
  • pageX 和 pageY

  • 是相对于整个页面的坐标点, 不管有没有滚动, 都是相对于页面拿到的坐标点

* {
	margin: 0;
	padding: 0;
}
body {
	width: 2000px;
	height: 2000px;
}
div {
	width: 300px;
	height: 300px;
	padding: 20px;
	border: 10px solid #333;
	margin: 20px 0 0 30px;
}

<div></div>

var oDiv = document.querySelector('div')

// 注册点击事件
oDiv.onclick = function (e) {
	// 事件对象兼容写法
	e = e || window.event

	console.log(e.pageX)
	console.log(e.pageY)
}

实现鼠标拖拽(无边界)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        div {
            height: 200px;
            width: 200px;
            background-image: linear-gradient(lightblue, lightpink);
            position: absolute;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        var box = document.querySelector('div')
        // 开关变量
        var flag = false;//默认关闭,禁止执行
        // 本身点击的
        box.onmousedown = function (eve) {
            flag = true;//打开开关,允许移动
            // 开始移动
            // 使用box再次点击才可以,document不会
            document.onmousemove = function (e) {
                if (!flag) return //判断开关是否可以执行移动
                // 移动最新坐标 - 本身按下的坐标  =  移动距离
                console.log(box.style.left = e.clientX - eve.offsetX + 'px');
                console.log(box.style.top = e.clientY - eve.offsetY + 'px');
            }
        }
        box.onmouseup = function () {
            flag = false //关闭开关,禁止执行
        }
    </script>
</body>
</html>
//详细版本
var box = document.querySelector('.box')
        var flag = false
        // 保存鼠标按下时的 定位
        var startX = 0
        var startY = 0
        // 保存鼠标按下时的 位置(偏移量)
        var startLeft = 0
        var startTop = 0
        box.onmousedown = function (e) {
            flag = true
            // console.log('鼠标按下', e.clientX, e.clientY)
            // 按下时 保存 鼠标的定位
            startX = e.clientX
            startY = e.clientY
            // 按下时 保存 元素的偏移量
            startLeft = box.offsetLeft
            startTop = e.target.offsetTop
        }
        document.onmousemove = function (e) {
            if (!flag) return
            // console.log('鼠标移动前的定位', startX, startY)
            // console.log('鼠标移动后的定位', e.clientX, e.clientY)
            // 3.1 获取最新的鼠标定位 - 鼠标按下时的定位 === 移动距离
            var moveX = e.clientX - startX
            var moveY = e.clientY - startY
            // 4.1 元素的初始位置 + 移动的距离 === 移动到哪里
            var left = startLeft + moveX
            var top = startTop + moveY
            box.style.left = left + 'px'
            box.style.top = top + 'px'
        }
        box.onmouseup = function () {
            flag = false
            console.log('鼠标抬起')
        }

猜你喜欢

转载自blog.csdn.net/weixin_42981560/article/details/132680552