網頁座標 - 應用篇

我現在要做的功能是:讓小怪獸跟著滑鼠移動

我的 codepen 範例

https://codepen.io/saffranwang/full/QWwOWxm

html:

🎃 有一個div叫做「.mouseImg」,裡面放入小怪獸的圖片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<body id="body">
<div class="wrap">
<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>
</div>
<div class="mouseImg">
<img src="https://i.ibb.co/mDXfzg3/2-03.png" width="100">
</div>

<script src="js/all.js"></script>

</body>

css:

🎃 在<body>把「“滑鼠游標”隱藏起來」: cursor: none;

🎃 在.mouseImg設定「position: fixed;」–> 圖片會固定在網頁上

🍋 position: fixed;在 css 這裡,並沒有寫「topleft」的值,因為我要用 JS 來控制它的「topleft」的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
body{
margin: 0;
padding: 0;
cursor: none;
}
html{
height: 100%;
}
.wrap{
max-width: 1920px;
height: 5000px;
background-color: #404747;
background-image: url(https://i.ibb.co/M2rjV75/dark.png);
background-position: bottom;
background-repeat: no-repeat;
}
.header{
height: 150px;
position: fixed;
top: 0;
width: 100%;
color: #fff;
text-align: center;
background-color: peru;
}
.header p{
padding: 0.5em;
}
.mouseImg{
position: fixed;
}

.style來修改「指定元素的style樣式」

🎃 建立變數mouseImg,來選取「.mouseImg」:
var mouseImg = document.querySelector('.mouseImg');

🎃 用.style來修改「指定元素的style樣式」

🍋 修改mouseImg的「style="left: "」,讓left等於「滑鼠在“瀏覽器視窗”的 X 座標」: mouseImg.style.left = e.clientX + 'px';

🍋 修改mouseImg的「style="top: "」,讓top等於「滑鼠在“瀏覽器視窗”的 Y 座標」: mouseImg.style.top = e.clientY + 'px';

JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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');
var mouseImg = document.querySelector('.mouseImg');

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;
mouseImg.style.left = e.clientX + 'px';
mouseImg.style.top = e.clientY + 'px';
}

var el = document.body;
el.addEventListener('mousemove', getPosition, false);

😄 JS 程式碼寫完了!

用開發者工具來看,

🎃 在.mouseImg裡面,寫上了「style="left: 417px; top: 163px;"」,就跟計算出來的滑鼠座標「clientX: 417, clientY: 163」一樣