如何实现每行字体大小递增10%的前端文本重复展示程序?
Fixing the Font Size Increment Issue
Hey there! I see the problem with your current code—your font size calculation is generating invalid CSS values like 10%0 or 10%1, which the browser can't interpret correctly. Let's fix that to get the 10% per-line increment working as you want.
The Root of the Problem
This line is where things go wrong:
output += "<div " + "style=\"font-size: 10%"+i+"\" " + " >" + text + "</div>" + "<br />";
When i is 0, it creates font-size: 10%0—that's not a valid percentage value. Instead, we need to calculate a percentage that increases by 10% for each iteration of the loop.
The Corrected Solution
We'll start with a reasonable base font size (like 100%, which matches default text size) and add 10% for each new line. Here's the fixed, cleaner version of your code:
<h2>Write your text here</h2> <input type="text" id="text" value="" /> <br /> <h2>How many times do you want to see it?</h2> <!-- Use number input to avoid non-numeric entries --> <input type="number" id="ggr" value="" min="1" /> <br /> <input type="button" value="Resultat" onClick="addElement();"/> <br /> <div id="result"></div> <script> function addElement() { var text = document.getElementById("text").value; // Handle invalid input by defaulting to 1 repeat var repeatCount = parseInt(document.getElementById("ggr").value) || 1; var output= ""; for(var i=0; i < repeatCount; i++) { // Calculate font size: start at 100%, add 10% per line var fontSize = 100 + (10 * i); // Use template literals for cleaner string building output += `<div style="font-size: ${fontSize}%">${text}</div><br />`; } document.getElementById("result").innerHTML = output; } </script>
Key Improvements Explained:
- Valid Font Size Math:
100 + (10 * i)gives us a valid percentage that starts at 100% (first line) and jumps by 10% each time (110%, 120%, etc.). If you want a smaller starting size, just swap100for your preferred base percentage (like 80%). - User-Friendly Input: Changed the repeat count field to
type="number"withmin="1"to prevent users from entering non-numeric values, which avoids unexpected behavior. - Cleaner Code: Used ES6 template literals (backticks
`) to replace messy string concatenation—this makes the HTML output easier to write and read. - Input Safety: Added
parseInt(...) || 1to handle cases where the user leaves the repeat count blank or enters garbage, defaulting to 1 repetition instead of breaking the code.
内容的提问来源于stack exchange,提问作者J. Doe Foe
相关产品推荐
相关产品推荐

