1. 程式人生 > >從獲取點選事件根元素談 target和currentTarget

從獲取點選事件根元素談 target和currentTarget

事情由來:

       寫了一個點選事件,想獲取根元素,想的直接用current就行了,因為之前就是這麼用的,但是之前的點選元素是沒子元素的,current就是根元素,但是這次點選元素內部有子元素,current就是點選到的元素,點選子元素,獲取的就是子元素,但是需求是無論點選元素哪裡,都要獲取到根元素,找了資料發現了 current 和currentTarget.

看程式碼:

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
   <style type="text/css" media="screen">
   	 .container1 {
   	 	width: 200px;
   	 	height: 50px;
   	 	border: 1px solid black;
   	 	float: right;
   	 }
   	 .container1 .item {
        border: 1px solid red;
        height: 20px;
        width: 50px;
   	 }
   </style>
   <div class="container1" onclick="click1(event)">
      內容111 
   	  <div class="item"></div>
   </div>
</body>
<script type="text/javascript">
	function click1 (e) {
      console.log('target')
      console.log(e.target)
      console.log('currentTarget')
      console.log(e.currentTarget)
	}
</script>
</html>

效果如下: 

 

可以看出 current就是點選的當前元素,currentTarget 是繫結點選事件的根元素。