1. 程式人生 > 實用技巧 >js的事件委派

js的事件委派

事件委派就是把子元素的事件繫結在父元素身上,通過判斷事件目標的不同,做不同的事 e.target;

以下為事件委派的案例:

<!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; } .wrap{ width: 200px; height: 200px; margin: 100px auto; padding: 50px 0; background-color: #ccc; } </style> </head> <body> <div class="wrap"> <h1 class="title">我是段落,點我文字變紅</h1> <div id="tex">我是div,點我背景變藍</div> <span>我是span,點我大小變30px</span> </div> <script> //
事件委派 var objWrap=document.querySelector('.wrap'); objWrap.onclick=function(e){ var elm=e.target; if(elm.className==='title'){ elm.style.color='red' }else if(elm.id==='tex'){ elm.style.backgroundColor='skyblue' }
else if(elm.tagName==='SPAN'){ elm.style.fontSize='30px'; } } </script> </body> </html>