當頁面元素觸發事件的時候, 該元素的容器以及整個頁面都會按照特定的順序響應該元素的觸發事件,事件傳播的順序叫作事件流。web
一、事件流分類:瀏覽器
冒泡型事件: 全部瀏覽器都支持,由明確的事件源到最不肯定的事件源依次向上觸發。函數
捕獲型事件:(IE不支持) 不肯定的事件源到明確的事件源依次向下觸發。this
二、傳統事件:spa
` div1.onclick = function(){ console.log(1); }; div2.onclick = function(){ console.log(2); }; div3.onclick = function(){ console.log(3); }`
三、現代事件:須要綁定的事件名稱只須要寫後面的,‘on’可不寫;最後一個語句是判斷處於捕獲階段仍是冒泡階段(true:捕獲階段;false:冒泡階段)code
`function fn(){ console.log('hello'); } div3.addEventListener('click',fn,false)`
四、傳統事件和現代事件的區別:orm
阻止冒泡事件:對象
`div.removeEventlistener` 移除
對於最裏層的節點來講,捕獲階段和冒泡階段的事件,哪一個事件先綁定,就會先執行哪一個事件。事件
IE: event.cancelBubble = true;ip
FF: event.stopPropagation();
`input.onkeydown = function(e){ if(e.keyCode === 67 && e.altKey === true){ alert('觸發快捷鍵'); } };`
一、阻止事件流
` div1.onclick = function(){ alert(1); }; div2.onclick = function(){ alert(2); }; div3.onclick = function(event){ //系統申明形參 //在標準瀏覽器下 var event = 事件對象; //在ie瀏覽器下 var event = undefined; //alert(3); //兼容兩個瀏覽器 //if(event === undefined){ // event = window.event; //} //也可簡寫爲: event = event || window.event; if(event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble = true; } alert(3); };`
二、阻止事件的默認行爲
`input.addEventListener('keydown',function(event){ console.log('hello'); event.preventDefault(); },false)`
在傳統事件中,還能夠使用return false的方式來阻止事件的默認行爲
` input.onkeydown = function(event){ console.log('hello'); //event.preventDefault(); return false; }`
(event.preventDefault();方式兩種均可以使用,推薦使用此方法)
div在瀏覽器中隨意拖拽:
`(function(){ var div =document.getElementById('tuo'); //頁面剛加載完成時,div距離頁面左側和頂部的距離 div.initPosition = { x:div.getBoundingClientRect().left, y:div.getBoundingClientRect().top }; //設置位置 function setPosition(x,y){ div.style.WebkitTransform = 'translate(' + x + 'px,' + y + 'px)'; div.style.OTransform = 'translate(' + x + 'px,' + y + 'px)'; div.style.MozTransform = 'translate(' + x + 'px,' + y + 'px)'; div.style.msTransform = 'translate(' + x + 'px,' + y + 'px)'; div.style.transform = 'translate(' + x + 'px,' + y + 'px)'; } div.addEventListener('mousedown',function(event){ //獲取當前鼠標按下的時候,鼠標在div內部的座標 this.downPosition = { x:event.offsetX, y:event.offsetY }; document.addEventListener('mousemove',hanleMouseMove,false); document.addEventListener('mouseup',releaseMouse,false); },false); //鼠標移動時候的事件處理函數 function hanleMouseMove(event){ var x = event.clientX - div.downPosition.x - div.initPosition.x; var y = event.clientY - div.downPosition.y - div.initPosition.y; setPosition(x,y); } //鼠標擡起時的事件處理函數 function releaseMouse(){ document.removeEventListener('mousemove',hanleMouseMove,false); document.removeEventListener('mouseup',releaseMouse,false); } })();`