如標題所述,我想在輸入 50 個或更多值后更改 textarea 的字體大小。例如,我的 textarea 的正常字體大小是 20px,但是當我輸入大于或等于 50 個字符的內容時,字體大小會變為 14px。
我試著做
let textArea = document.getElementById("post");
var maxNumOfChars = 50;
const countCharacters = () => {
let numOfEnteredChars = textArea.value.length;
};
textArea.addEventListener("inputs", countCharacters);
if(numOfEnteredChars >= 50) {
textArea.style.fontSize = "1px";
}
<textarea name="post" placeholder="What's on you mind?" id="post"></textarea>
當然,我的代碼有問題(我是 javascript 初學者),所以請更正我的代碼或采取更好的方法。謝謝
uj5u.com熱心網友回復:
首先-事件必須是input,而不是inputs
另一件事 - 是更正的業務邏輯
const textArea = document.getElementById('post');
const resizeTextArea = () => {
textArea.style.fontSize = textArea.value.length <= 50 ? '20px' : '14px';
};
textArea.addEventListener('input', resizeTextArea);
<textarea id="post"></textarea>
uj5u.com熱心網友回復:
您countCharacters是一個不回傳任何內容的 void 函式。并且numOfEnteredChars函式內部的變數只能在該函式的范圍內訪問。您無法在函式之外訪問它。
let textArea = document.getElementById("post");
textArea.addEventListener('input', () => {
textArea.value.length < 50 ? textArea.style.fontSize = '50px' : textArea.style.fontSize = '14px'
})
為我作業!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/494309.html
標籤:javascript html
