快速掌握HTML、CSS、JS实现用户输入与表格展示
2023-12-15 11:32:22
利用 HTML、CSS 和 JavaScript 轻松实现用户输入和表格展示
初探 HTML:构建网页框架
HTML,超文本标记语言,是网页的基石。就像一栋建筑的地基,它定义了网页的结构和内容。利用 HTML,你可以创建标题、段落、链接和其他基本元素。
代码示例:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>用户输入与表格展示</h1>
<form>
<label for="name">姓名:</label>
<input type="text" id="name">
<br>
<label for="age">年龄:</label>
<input type="number" id="age">
<br>
<input type="submit" value="提交">
</form>
<table id="result">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
CSS:美化你的网页
CSS,层叠样式表,是网页的外衣。它控制着字体、颜色、背景等外观元素,让你的网页焕然一新。
代码示例:
body {
font-family: Arial, sans-serif;
font-size: 16px;
}
h1 {
color: #333;
font-size: 24px;
margin-bottom: 10px;
}
form {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"],
input[type="number"] {
width: 200px;
padding: 5px;
margin-bottom: 5px;
}
input[type="submit"] {
background-color: #008CBA;
color: white;
padding: 5px 10px;
border: none;
border-radius: 5px;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 5px;
border: 1px solid #ccc;
}
th {
background-color: #eee;
}
JavaScript:为网页注入活力
JavaScript,网页的灵魂,为用户交互提供了生命力。它让你能够提交表单、显示数据,甚至创建游戏和应用程序。
代码示例:
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const name = document.querySelector('#name').value;
const age = document.querySelector('#age').value;
// 在表格中添加一行数据
const tableBody = document.querySelector('#result tbody');
const newRow = document.createElement('tr');
const newNameCell = document.createElement('td');
const newAgeCell = document.createElement('td');
newNameCell.textContent = name;
newAgeCell.textContent = age;
newRow.appendChild(newNameCell);
newRow.appendChild(newAgeCell);
tableBody.appendChild(newRow);
});
大功告成!
现在你已经掌握了如何利用 HTML、CSS 和 JavaScript 实现用户输入和表格展示的功能。快去尝试,创造令人惊叹的交互式网页吧!
常见问题解答
1. 如何让输入字段成为必填项?
在 <input>
标签中添加 required
属性,例如:<input type="text" id="name" required>
2. 如何限制用户输入的年龄范围?
在 <input>
标签中使用 min
和 max
属性,例如:<input type="number" id="age" min="1" max="120">
3. 如何自动聚焦到第一个输入字段?
在 <input>
标签中添加 autofocus
属性,例如:<input type="text" id="name" autofocus>
4. 如何使用 JavaScript 验证用户输入?
使用 JavaScript 的 validation
API,例如:
const nameInput = document.querySelector('#name');
if (nameInput.value === '') {
alert('请输入姓名!');
}
5. 如何使用 CSS 创建更美观的表格?
使用 CSS 的 table
和 td
选择器,调整表格外观,例如:
table {
background-color: #eee;
}
td {
text-align: center;
font-weight: bold;
}