添加事件addEventListener,删除事件removeEventListener
<body>
<div>1111</div>
<div>2222</div>
<div>3333</div>
<script>
var divs=document.querySelectorAll('div');
divs[0].onclick = function (){
alert(11);
//1.传统方式删除事件
divs[0].onclick= null;
}
//添加事件,删除事件
divs[1].addEventListener('click',fn);
function fn(){
alert(22);
divs[1].removeEventListener('click',fn);
}
</script>
</body>
DOM事件流
- JS 代码中只能执行捕获或者冒泡其中的一个阶段。
- onclick 和addachEvent(ie) 只能得到冒泡阶段
- 捕获阶段 如果addEventListener 第三个参数是true,那么则处于捕获阶段 document - > html - > body -> father - > son
<body>
<div class="father">
<div class="son">son儿子</div>
</div>
<script>
//dom 事件流 三个阶段
//1. JS 代码中只能执行捕获或者冒泡其中的一个阶段。
//2. onclick 和addachEvent(ie) 只能得到冒泡阶段
//3. 捕获阶段 如果addEventListener 第三个参数是true,那么则处于捕获阶段 document - > html - > body -> father - > son
// var son = document.querySelector('.son');
// son.addEventListener('click',function (){
// alert('son');
// //看这个地方是true所以 是捕获阶段顺序执行,先father
// },true);
// var father = document.querySelector('.father');
// father.addEventListener('click',function (){
// alert('father');
// },true);
//4.冒泡阶段 son -> father -> body -> html -> document
var son = document.querySelector('.son');
son.addEventListener('click',function (){
alert('son');
//阻止冒泡方式
e.stopPropagation();
//阻止事件冒泡的第二种方式
e.cancelBubble = true;
//看这个地方是true所以 是捕获阶段顺序执行,先father
},false);
var father = document.querySelector('.father');
father.addEventListener('click',function (){
alert('father');
},false);
</script>
</body>
事件委托
事件委托也称为事件代理,在JQuery里面称为事件委派。
事件委托的原理
不是每个子节点单独设置事件监听器,而是事件监听器设置在父结点上,然后利用冒泡原理设置每个子节点。
作用
只操作一次dom,提高程序的性能。
如以下例子,给每个 li 设置点击事件的话会比较麻烦,但是给ul设置点击事件的话就会相对容易。
<body>
hao are you
<ul>
<li>知否知否应是绿肥红瘦</li>
<li>知否知否应是绿肥红瘦</li>
<li>知否知否应是绿肥红瘦</li>
<li>知否知否应是绿肥红瘦</li>
<li>知否知否应是绿肥红瘦</li>
</ul>
<script>
var ul=document.querySelector('ul');
ul.addEventListener('click',function (){
// alert('知否知否应是绿肥红手')
e.target.style.background = 'cyan'
})
//禁止右键选中
document.addEventListener('contextmenu',function (e){
e.preventDefault();
})
//禁止鼠标选择
document.addEventListener('selectstart',function (e){
e.preventDefault();
})
</script>
</body>
举例
跟随鼠标移动的图片
<style>
img{
width: 30px;
height: 30px;
position: absolute;
top: 2px;
}
</style>
<body>
<img src="../first/image/bird.jpg">
<script>
var img = document.querySelector('img')
document.addEventListener('mousemove',function (e){
var x = e.pageX;
var y = e.pageY;
console.log('x坐标是'+x,'y坐标是'+y);
img.style.left=x-15 + 'px';
img.style.top=y-15 + 'px';
})
</script>
</body>
常用的键盘事件
模仿京东按键输入
<input type="text">
<script>
var input=document.querySelector('input')
document.addEventListener('keyup',function (e){
if (e.keyCode === 83){
input.focus();
}
})
</script>