前面提到那個e,蘊含著我們與網頁互動豐富的資訊。
例如:
我做了一個列表,裡面放了倚天劍、屠龍刀還有碧血劍。
<ul id="box">
<li class="sky">倚天劍</li>
<li class="dragon">屠龍刀</li>
<li class="blood">碧血劍</li>
</ul>
<h1>顯示e的資訊</h1>
<ul>
<li>target: <span class="target"></span></li>
<li>tagName: <span class="tagName"></span></li>
<li>className: <span class="className"></span></li>
<li>textContent: <span class="textContent"></span></li>
<li>screenX: <span class="screenX"></span></li>
<li>screenY: <span class="screenY"></span></li>
<li>pageX: <span class="pageX"></span></li>
<li>pageY: <span class="pageY"></span></li>
<li>clientX: <span class="clientX"></span></li>
<li>clientY: <span class="clientY"></span></li>
</ul>
然後從列表的ul標籤來監聽滑鼠的點擊事件,讓getInformation這個函式去捉「事件物件」(event)裡面的資訊。
var el = document.getElementById('box');
var target = document.querySelector('.target')
var tagName = document.querySelector('.tagName');
var className = document.querySelector('.className');
var content = document.querySelector('.textContent');
var screenX = document.querySelector('.screenX');
var screenY = document.querySelector('.screenY');
var pageX = document.querySelector('.pageX');
var pageY = document.querySelector('.pageY');
var clientX = document.querySelector('.clientX');
var clientY = document.querySelector('.clientY');
function getInformation (e) {
target.textContent = e.target;
tagName.textContent = e.target.tagName;
className.textContent = e.target.className;
content.textContent = e.target.textContent;
screenX.textContent = e.screenX;
screenY.textContent = e.screenY;
pageX.textContent = e.pageX;
pageY.textContent = e.pageY;
clientX.textContent = e.clientX;
clientY.textContent = e.clientY;
}
el.addEventListener('click', getInformation, false);
https://codepen.io/popeye_ux/pen/VwbWrXL
可以到Codepen看看我做的範例,應該有進一步的體會。