My task is to increase and decrease the size of a "balloon" when pressing the Up and Down arrow keys, respectively. I have set it up as a
tag in HTML and when pressing those keys it has to set the fontsize to something bigger or smaller by 10%. Yet it doesn't work. The size remains the same.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event tasks</title>
</head>
<body>
<p style="font-size: 24px;">??</p>
<button id="temp">Temp</button>
<script src="tasks.js"></script>
</body>
</html>
JS:
const balloon = document.querySelector('p');
const defaultSize = balloon.style.fontSize;
balloon.addEventListener('keydown', event => {
let size = balloon.style.fontSize;
if (event.key == 'ArrowUp') {
/*size += 0.1 * size;
balloon.style.fontSize = size + 'px';*/
setSize(size * 1.1);
event.preventDefault();
}
else if (event.key == 'ArrowDown') {
while (size > defaultSize) {
/*size -= 0.1 * size;
balloon.style.fontSize = size + 'px';*/
setSize(size * 0.9);
event.preventDefault();
}
}
});
function setSize(newSize) {
size = newSize;
balloon.style.fontSize = size + "px";
}
document.getElementById('temp').addEventListener('click', () => {
setSize(40);
});
I set a constant to the p element that holds the balloon symbol and the starting size, to be used when decreasing its size so it couldn't go past a certain size. Next is just listening for the event and if the key is ArrowUp (I tried using the number of the Arrow Up and it didn't work either) then increase the size or if it's ArrowDown, decrease the size. I also override the default behaviour since I'm not sure what it is. The setSize function is temporary, just like the button, to see if either I didn't write the size increase procedure correctly or something else is at fault.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…