1 事件冒泡
子元素触发的事件,会往上(父元素)传递;
例子:
- <div id="box">
- <p></p>
- </div>
- <script>
- var oP = document.querySelector('#box p');
- var oBox = document.querySelector('#box');
-
- oBox.onclick = function () {
- alert('123');
- }
- </script>
当我点击div中的p标签时,也会触发onclick,这是为什么?
因为事件会一直往上传递,p -> div(触发)->body ->document
冒泡事件是默认事件,但有些情况,冒泡事件是一种麻烦的事情。如:
- <div id="box">
- <p class="detail">
- 我是detail!
- </p>
- </div>
//我的目的本来是,点击div弹出p标签,点击document时隐藏p标签。 - var oBox =document.querySelector('#box');
- var oP = oBox.children[0];
-
- //我点击oBox时弹出p标签
- oBox.onclick = function () {
- oP.style.display = 'block';
- };
- //但随着冒泡的传递,到了document时,也会触发document标签的点击事件,然后p标签刚出现的瞬间又隐藏了
- document.onclick = function () {
- oP.style.display = 'none';
- oP.style.display = 'none';
- };
这时候需要把默认事件去掉
cancelBubble = false 或者 stopPropagation();
- //上述的oBox的点击事件改成
- oBox.onclick = function (e) {
- oP.style.display = 'block';
- e = e||window.event;
- e.cancelBubble = true;
- 或者 e.stopPropagation();
- };
另外:
- e.cancelBubble = true;是兼容所有浏览器的
e.stopPropagation() 不兼容IE8以下,所以一般都推荐第一种
-
2 onmouseenter/onmouseleave 和onmouseover/onmouseout区别

- <div id="box1">1
- <div id="box2">2
- <div id="box3">3</div>
- </div>
- </div>
- <script>
- var oB1 = document.querySelector('#box1');
- oB1.onmouseenter=function () {
- console.log('enter');
- }
- oB1.onmouseleave=function () {
- console.log('leave');
- }
- /*oB1.onmouseover=function () {
- console.log('over');
- }
- oB1.onmouseout=function () {
- console.log('out');
- }*/
- </script>
onmouseenter/onmouseleave:在移入到子元素时会触发;
当鼠标从外部移入3触发onmouseenter ,再移入2触发(3的onmouseleave)和(2的onmouseenter),在移入1触发(2的onmouseleave)和(1的onmouseenter);
onmouseover/onmouseout:不会受子元素影响
当鼠标同上移入3触发onmouseover,但继续移入到2和1中时,并不会触发onmouseover事件,当鼠标移出3到外部时才触发onmouseleave。
3 阻止默认事件 (两种方法)
1> event.preventDefault();
2>return false;
return false:相当于 event.preventDefault() + event.cancelBubble = false + event.stopPrapagation() 的集合;
4 键盘事件
事件:onkeydown 、 onkeypress 、onkeyup
键值:event.keyCode
- document.onkeydown = function (e) {
- e = e||window.event;
- console.log( e.keyCode );
- if (e.keyCode === 116){
- e.preventDefault();
- }
- }
onkeydown:
按下时触发,假设不抬起,会持续(多次)触发
onkeypress:
和onkeydown类似,但是只响应能键入值的键(比如ctrl 是不能键入值的,所以不能响应)
onkeyup:
抬起键时触发,一次抬起触发一次
又:
onkeydown在键入值之前触发
onkeyup在键入值之后触发
- <input type="text" id="txt" />
- <script>
- var oTxt = document.querySelector('#txt');
-
- /*
- oTxt.onkeydown = function (e) {
- console.log( this.value );
- }*/
-
- oTxt.onkeyup = function (e) {
- console.log( this.value );
- }
- </script>
在input框中:
oTxt.onkeydown: 依次输入1,2,3,4 console中依次出现:1,12,123。 也就是说知道按下一个键时,才会触发上一个事件

oTxt.onkeyup: 依次输入1,2,3,4 console中依次出现:1,12,123, 1234。是同步进行的。
