整理網頁座標 了解 screen、page、client 差異
event 物件能夠告訴你當事件被觸發,游標所在位置。
顯示 screen、page、client X跟Y軸的數字
<div class="header">
<p>
screenX: <span class="screenX"></span>
screenY: <span class="screenY"></span>
</p>
<p>
pageX: <span class="pageX"></span>
pageY: <span class="pageY"></span>
</p>
<p>
clientX: <span class="clientX"></span>
clientY: <span class="clientY"></span>
</p>
</div>
2.宣告 screen、page、client X跟Y軸
let screenX =document.querySelector('.screenX');
let screenY =document.querySelector('.screenY');
let pageX =document.querySelector('.pageX');
let pageY =document.querySelector('.pageY');
let clientX = document.querySelector('.clientX');
let clientY = document.querySelector('.clientY');
3.命名getPosition的 function,用textContent來對應各自數值
function getPosition(e){
screenX.textContent = e.screenX;
screenY.textContent = e.screenY;
pageX.textContent = e.pageX;
pageY.textContent = e.pageY;
clientX.textContent = e.clientX;
clientY.textContent = e.clientY;
}
4.宣告el指定body,並監聽滑鼠移動
var el = document.body;
el.addEventListener('mousemove', getPosition, false);
練習滑鼠指標黏住一顆球,隨著滑鼠移動跟著移動,透過clientX跟Y軸的數字,等同於球的上邊左邊距離邊線的數值
滑鼠指標通常是左上角開始計算
5.建構一顆球與CSS
//Html
<body>
<div class="mouseball"></div>
</body>
//Css
.mouseball{
width: 50px;
height: 50px;
position: fixed;
//固定網頁位置
border-radius:50% 50%; background: #000;
}
6.JS部分,先宣告clientX軸跟Y軸,再來那顆球
var clientX = document.querySelector('.clientX');
var clientY = document.querySelector('.clientY');
var mouseBall = document.querySelector('.mouseball');
7.
命名getPosition的 function,
function getPosition(e) {
clientX.textContent = e.clientX;
clientY.textContent = e.clientY;
mouseBall.style.left =e.clientX+'px';
mouseBall.style.top =e.clientY+'px';
}
8.宣告el指定body,並監聽滑鼠移動
var el = document.body;
el.addEventListener('mousemove', getPosition, false);