HTML,CSS 和 JavaScript 创建一个简单的文字计数器 - 项越资源网-html css js 用法分享社区-开发交流-项越资源网

HTML,CSS 和 JavaScript 创建一个简单的文字计数器

Step 1: HTML

First, let’s create the skeleton of the Text Counter using HTML.

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <title>Text Counter</title>
    <p>Please enter a string of text below:</p>
    <textarea id="txt-input" rows="10" cols="50"></textarea>
    <button type="submit" onclick="calculate()">Calculate</button>
    <p id="txt-output"></p>

Step 2: CSS

Now we need to add some styling with CSS:

body { 
  font-family: sans-serif;
  margin: 0 auto;
  width: 400px;
button { 
  background-color: #00f;
  border: none;
  color: #fff;
  padding: 10px;

Step 3: JavaScript

Lastly, we’ll need to write some JavaScript for the text counter logic:

function calculate() {
  var str = document.getElementById("txt-input").value;
  var words = str.split(" ");
  var wordCount = words.length;

  document.getElementById("txt-output").innerHTML = "Word Count: " + wordCount;