繁体   English   中英

如何在Javascript中使用'ArrowUp'增加表情符号的大小

[英]How to increase size of emoji using 'ArrowUp' in Javascript

我正在尝试不断增加气球表情符号10px的大小,当用户按下向上箭头以及用键盘上的向下箭头减小10px的大小。

我一直试图设置:

let size = para.style.fontSize;

为了获得大小的变量,然后通过在我的函数中添加+/- 10px来调整该值。 但是,我尝试过这种方法,似乎你无法设置:

para.style.fontSize = size +10;

有没有人有任何建议让这个工作?

注意:我没有在下面的代码中包含size变量,因为我发现它不起作用。

 <!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p { font-size: 50px; } </style> </head> <body> <p>🎈</p> <script> let para = document.querySelector('p'); window.addEventListener("keydown", e => { if (e.key == "ArrowUp") { para.style.fontSize = '60px'; } else { para.style.fontSize = '40px'; } }); </script> </body> </html> 

要在多个keydown事件上实现增长/收缩行为,您需要为每个事件递增/递减para.style.fontSize 一旦完成,可以如下:

 <!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p { font-size: 50px; } </style> </head> <body> <p>🎈</p> <script> let para = document.querySelector('p'); window.addEventListener("keydown", e => { let currentSize = parseInt(para.style.fontSize); // If unable to determine current fontSize, default to 50 if (isNaN(currentSize)) { currentSize = 50; } // Define the rate of change let changeAmount = 5; if (e.key == "ArrowUp") { para.style.fontSize = (currentSize + changeAmount) + 'px'; } else { // Protect againt zero or negative font sizes via Math.max() para.style.fontSize = Math.max(changeAmount, currentSize - changeAmount) + 'px'; } }); </script> </body> </html> 

问题是当前的fontSize属性为null,因此您无法添加空值。 第二个问题是fontSize属性实际上是一个带有“px”的字符串。 因此,如果要增加或减少该值,则需要解析整数值。 然后,当您将其分配回para.style.fontSize时,您需要追加“px”。

这是您的代码,其中包含上述更改。

 <!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p { font-size: 50px; } </style> </head> <body> <p>🎈</p> <script> let para = document.querySelector('p'); // Set to default size para.style.fontSize = '24px'; window.addEventListener("keydown", e => { var sizeAsInteger = parseInt(para.style.fontSize, 10); if (e.key == "ArrowUp") { sizeAsInteger += 10; } else { sizeAsInteger -= 10; } para.style.fontSize = sizeAsInteger + 'px'; }); </script> </body> </html> 

请注意,如果您获取size然后执行console.log(size) ,您将获得第一轮的空白结果(因为它最初未设置),并且所有后续轮次都会获得大小并将px附加到末尾。 因此, size + 10 ,初始尺寸为40px将为您提供40px10 这导致不期望的行为。

要解决此问题,您需要删除px ,转换为数字,然后再次附加px

 <!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p { font-size: 50px; } </style> </head> <body> <p>🎈</p> <script> let para = document.querySelector('p'); window.addEventListener("keydown", e => { let size = para.style.fontSize.replace('px', ''); size = size == '' ? '50' : size; // size may not be initialized, so default to our intended starting value! size = parseInt(size); if (e.key == "ArrowUp") { para.style.fontSize = (size + 10) + 'px'; } else { para.style.fontSize = (size - 10) + 'px'; } }); </script> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM