要实现一个类似QQ的联系人列表,我们可以使用JavaScript结合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>QQ联系人列表</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="contact-list">
<ul id="contacts"></ul>
</div>
<form id="add-contact-form">
<input type="text" id="name" placeholder="姓名">
<input type="text" id="phone" placeholder="电话">
<button type="submit">添加联系人</button>
</form>
<script src="script.js"></script>
</body>
</html>
body {
font-family: Arial, sans-serif;
}
#contact-list {
width: 300px;
margin: auto;
}
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #ddd;
}
form {
margin-top: 20px;
}
document.addEventListener('DOMContentLoaded', function() {
const contactsList = document.getElementById('contacts');
const addContactForm = document.getElementById('add-contact-form');
const nameInput = document.getElementById('name');
const phoneInput = document.getElementById('phone');
// 模拟存储联系人数据
let contacts = [];
// 加载已有联系人
function loadContacts() {
contactsList.innerHTML = '';
contacts.forEach(contact => {
const li = document.createElement('li');
li.textContent = `${contact.name} - ${contact.phone}`;
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除';
deleteButton.onclick = function() {
deleteContact(contact);
};
li.appendChild(deleteButton);
contactsList.appendChild(li);
});
}
// 添加联系人
addContactForm.onsubmit = function(event) {
event.preventDefault();
const name = nameInput.value.trim();
const phone = phoneInput.value.trim();
if (name && phone) {
contacts.push({ name, phone });
loadContacts();
nameInput.value = '';
phoneInput.value = '';
}
};
// 删除联系人
function deleteContact(contact) {
const index = contacts.indexOf(contact);
if (index > -1) {
contacts.splice(index, 1);
loadContacts();
}
}
});
localStorage
或服务器端数据库。通过上述代码和解释,你可以实现一个基本的QQ联系人列表功能,并了解相关的概念和技术细节。
领取专属 10元无门槛券
手把手带您无忧上云