Code for a moving block on html page
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative; /* Position relative for absolute positioning of child elements */
width: 100px;
height: 100px;
}
.quarter {
position: absolute;
width: 50px;
height: 50px;
}
.top-left {
background-color: blue;
top: 0;
left: 0;
}
.top-right {
background-color: green;
top: 0;
left: 50px;
}
.bottom-left {
background-color: red;
top: 50px;
left: 0;
}
.bottom-right {
background-color: magenta;
top: 50px;
left: 50px;
}
.square {
position: absolute;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="square">
<div class="container">
<div class="quarter top-left"></div>
<div class="quarter top-right"></div>
<div class="quarter bottom-left"></div>
<div class="quarter bottom-right"></div>
</div>
</div>
<script>
// Get the square element
const square = document.querySelector('.square');
const step = 10; // Number of pixels to move per key press
// Function to update the square's position
function moveSquare(x, y) {
const rect = square.getBoundingClientRect();
square.style.left = `${rect.left + x}px`;
square.style.top = `${rect.top + y}px`;
}
// Add a click event listener to the document body
document.addEventListener('click', function(event) {
// Get the click coordinates relative to the document
const x = event.clientX;
const y = event.clientY;
// Update the position of the square
square.style.left = `${x - square.offsetWidth / 2}px`;
square.style.top = `${y - square.offsetHeight / 2}px`;
});
// Add a keydown event listener to the document
document.addEventListener('keydown', function(event) {
switch (event.key) {
case 'ArrowUp':
moveSquare(0, -step);
break;
case 'ArrowDown':
moveSquare(0, step);
break;
case 'ArrowLeft':
moveSquare(-step, 0);
break;
case 'ArrowRight':
moveSquare(step, 0);
break;
}
});
</script>
</body>
</html>
Comments
Post a Comment