1. 程式人生 > 其它 >教你用JavaScript實現實時字元計數器

教你用JavaScript實現實時字元計數器

案例介紹

歡迎來到我的小院,我是霍大俠,恭喜你今天又要進步一點點了!
我們來用JavaScript程式設計實戰案例,做一個實時字元計數器。使用者在指定位置打字,程式實時顯示字元數量。

案例演示

在編輯框內輸入字元,下方實時記錄數字,且輸入有數量限制,輸入超出限制的字元後就無法再繼續輸入。

原始碼學習

進入核心程式碼學習,我們先來看HTML中的核心程式碼。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>小院裡的霍大俠</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <!-- 有個小院-興趣程式設計 -->
    <div class="container">
      <h2>有個小院-實時字元計數器</h2>
      <textarea
        id="textarea"
        class="textarea"
        placeholder="請在這裡輸入"
        maxlength="50"
        ></textarea>
      <div class="counter-container">
        <p>
          字元數:
          <span class="total-counter" id="total-counter"></span>
        </p>
        <p>
          字元總數:
          <span class="remaining-counter" id="remaining-counter"></span>
        </p>
      </div>
    </div>
    <script src="index.js"></script>
  </body>
</html>

然後再讓我們來看CSS程式碼,由於CSS程式碼不是重點且數量較多在這裡就不做過多介紹。

body {
  margin: 0;
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
  background-color: salmon;
  font-family: cursive;
}

.container {
  background-color: lightpink;
  width: 400px;
  padding: 20px;
  margin: 5px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  }

  .textarea {
  resize: none;
  width: 100%;
  height: 100px;
  font-size: 18px;
  font-family: sans-serif;
  padding: 10px;
  box-sizing: border-box;
  border: solid 2px darkgray;
  }

  .counter-container {
  display: flex;
  justify-content: space-between;
  padding: 0 5px;
  }

  .counter-container p {
  font-size: 18px;
  color: gray;
  }

  .total-counter {
  color: slateblue;
  }

  .remaining-counter {
  color: orangered;
  }

讓我們來編寫核心的JavaScript程式碼,通過getElementById繫結HTML元素;編寫鍵盤事件,當用戶敲擊鍵盤輸入字元,則更新字元數量;編寫更新字元數量函式,設定字元數為文字框的輸入字元長度,設定字元總數為文字框最大長度-字元數。

//有個小院-興趣程式設計
const textareaEl = document.getElementById("textarea");
const totalCounterEl = document.getElementById("total-counter");
const remainingCounterEl = document.getElementById("remaining-counter");

textareaEl.addEventListener("keyup", () => {
  updateCounter();
});

updateCounter()

function updateCounter() {
  totalCounterEl.innerText = textareaEl.value.length;
  remainingCounterEl.innerText =
    textareaEl.getAttribute("maxLength") - textareaEl.value.length;
}


記得關注我,每天學習一點點

你覺得這個案例還能應用到什麼地方?

全網可搜:小院裡的霍大俠, 免費獲取簡單易懂的實戰程式設計案例。程式設計/就業/副業/創業/資源。
私微信:huodaxia_xfeater
二維碼: http://www.yougexiaoyuan.com/images/weixin_huodaxia.jpg
公眾號:有個小院(微信公眾號:yougexiaoyuan)
github:yougexiaoyuan (視訊原始碼免費獲取)
(部分素材來源於網際網路,如有保護請聯絡作者)