Cho 1 biểu tượng vui nhộn có thể di chuyển theo chuột máy tính, từ ý tưởng này điều cần thực hiện là sử dụng thẻ <img>
hoặc thẻ <div>
có chứa hình ảnh cần thiết và di chuyển thẻ đó theo con trỏ chuột.
Hướng dẫn hiện thực
HTML
<!DOCTYPE html> <html> <body> <div id="id-object" class="object">POINTER</div> </body> </html>
CSS
<style> .object{ width:50px; height:20px; line-height:20px; background:#f80; color:#fff; text-align:center; font-size:1rem; cursor:context-menu; position:absolute; top:0; left:0; } </style>
Từ đoạn position: fixed
cho phép đối tượng nằm ở vị trí bất kỳ theo định nghĩa top: 0
, left: 0
JavaScript
Điều khiển việc thay đổi top
và left
của thẻ thay đổi theo tọa độ đang di chuyển của con trỏ chuột.
<script>
function init() {
window.addEventListener("mousemove", function (e) {
const x = window.Event
? e.pageX
: event.clientX +
(document.documentElement.scrollLeft
? document.documentElement.scrollLeft
: document.body.scrollLeft);
const y = window.Event
? e.pageY
: event.clientY +
(document.documentElement.scrollTop
? document.documentElement.scrollTop
: document.body.scrollTop);
let node = document.getElementById("id-object");
node.style.top = y - 10 + "px";
node.style.left = x - 25 + "px";
});
}
window.onload = init;
</script>
Đăng ký sự kiện theo dõi di chuyển chuột, khi phát sinh sự kiện này, tiến hành lấy tọa độ chuột và gán lại tọa độ cho đối tượng.
Codes hoàn chỉnh
Tạo file index.htm
và sao chép toàn bộ code bên dưới vào và mở bằng trình duyệt web.
<!DOCTYPE html>
<html>
<head>
<style>
.object {
width: 70px;
height: 20px;
line-height: 20px;
background: #f80;
color: #fff;
text-align: center;
font-size: 14px;
cursor: context-menu;
position: fixed;
top: 0;
left: 0;
}
</style>
<script>
function init() {
window.addEventListener("mousemove", function (e) {
const x = window.Event
? e.pageX
: event.clientX +
(document.documentElement.scrollLeft
? document.documentElement.scrollLeft
: document.body.scrollLeft);
const y = window.Event
? e.pageY
: event.clientY +
(document.documentElement.scrollTop
? document.documentElement.scrollTop
: document.body.scrollTop);
let node = document.getElementById("id-object");
node.style.top = y - 10 + "px";
node.style.left = x - 35 + "px";
});
}
window.onload = init;
</script>
</head>
<body>
<div id="id-object" class="object">POINTER</div>
</body>
</html>