HTML5 输入框带清除功能

在网页开发中,我们经常会遇到需要用户输入信息的情况。为了提高用户体验,我们可以在输入框中添加一个清除按钮,让用户可以方便地清空输入内容。本文将介绍如何使用HTML5和CSS实现带清除功能的输入框,并附上代码示例。

实现步骤

1. HTML结构

首先,我们需要在HTML中创建一个输入框和一个清除按钮。清除按钮可以是一个图标或者文字,我们可以使用Font Awesome等图标库来展示一个清除图标。

<input type="text" id="inputBox" placeholder="请输入内容">
<button id="clearBtn">清除</button>

2. CSS样式

接下来,我们可以使用CSS样式来美化输入框和清除按钮的样式。我们可以设置输入框的宽度、高度、边框样式等,并将清除按钮定位在输入框的右侧。

#inputBox {
  width: 200px;
  height: 30px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
}

#clearBtn {
  background: none;
  border: none;
  cursor: pointer;
  position: absolute;
  right: 5px;
  top: 5px;
}

3. JavaScript交互

最后,我们需要使用JavaScript来实现清除功能。当用户点击清除按钮时,我们可以清空输入框的内容。

document.getElementById('clearBtn').addEventListener('click', function() {
  document.getElementById('inputBox').value = '';
});

完整示例

下面是一个完整的示例代码,包括HTML、CSS和JavaScript部分。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>带清除功能的输入框</title>
<style>
#inputBox {
  width: 200px;
  height: 30px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
}

#clearBtn {
  background: none;
  border: none;
  cursor: pointer;
  position: absolute;
  right: 5px;
  top: 5px;
}
</style>
</head>
<body>
<input type="text" id="inputBox" placeholder="请输入内容">
<button id="clearBtn">清除</button>

<script>
document.getElementById('clearBtn').addEventListener('click', function() {
  document.getElementById('inputBox').value = '';
});
</script>
</body>
</html>

流程图

flowchart TD
    A[开始] --> B[创建输入框和清除按钮]
    B --> C[样式美化]
    C --> D[添加JavaScript交互]
    D --> E[结束]

甘特图

gantt
    title HTML5输入框带清除功能示例
    section 整体流程
    创建输入框和清除按钮 :done, 2021-10-01, 1d
    样式美化 :done, 2021-10-02, 1d
    添加JavaScript交互 :done, 2021-10-03, 1d

通过以上步骤,我们可以实现一个带清除功能的输入框,提高用户体验。希望本文对你有所帮助!