js实现@功能
实现@功能的JavaScript方法
监听输入事件
使用addEventListener监听输入框的input或keyup事件,检测用户是否输入了@符号。
const inputElement = document.getElementById('commentInput');
inputElement.addEventListener('input', function(event) {
const text = event.target.value;
const lastChar = text.slice(-1);
if (lastChar === '@') {
showUserList();
}
});
显示用户列表
当检测到@符号时,显示一个包含用户名的下拉列表供用户选择。
function showUserList() {
const userList = ['用户1', '用户2', '用户3'];
const dropdown = document.createElement('div');
dropdown.className = 'user-dropdown';
userList.forEach(user => {
const item = document.createElement('div');
item.textContent = user;
item.addEventListener('click', function() {
insertUsername(user);
dropdown.remove();
});
dropdown.appendChild(item);
});
document.body.appendChild(dropdown);
}
插入用户名
用户点击下拉列表中的用户名后,将用户名插入到输入框中@符号之后。
function insertUsername(username) {
const inputElement = document.getElementById('commentInput');
const text = inputElement.value;
const atIndex = text.lastIndexOf('@');
inputElement.value = text.slice(0, atIndex) + '@' + username + ' ';
inputElement.focus();
}
样式调整
为下拉列表添加基本样式,确保其显示在输入框下方。
.user-dropdown {
position: absolute;
border: 1px solid #ccc;
background: white;
max-height: 150px;
overflow-y: auto;
}
.user-dropdown div {
padding: 8px;
cursor: pointer;
}
.user-dropdown div:hover {
background: #f0f0f0;
}
完整示例
将上述代码整合到一个完整的HTML文件中,确保所有功能正常工作。

<!DOCTYPE html>
<html>
<head>
<style>
.user-dropdown {
position: absolute;
border: 1px solid #ccc;
background: white;
max-height: 150px;
overflow-y: auto;
}
.user-dropdown div {
padding: 8px;
cursor: pointer;
}
.user-dropdown div:hover {
background: #f0f0f0;
}
</style>
</head>
<body>
<textarea id="commentInput" rows="4" cols="50"></textarea>
<script>
const inputElement = document.getElementById('commentInput');
inputElement.addEventListener('input', function(event) {
const text = event.target.value;
const lastChar = text.slice(-1);
if (lastChar === '@') {
showUserList();
}
});
function showUserList() {
const userList = ['用户1', '用户2', '用户3'];
const dropdown = document.createElement('div');
dropdown.className = 'user-dropdown';
userList.forEach(user => {
const item = document.createElement('div');
item.textContent = user;
item.addEventListener('click', function() {
insertUsername(user);
dropdown.remove();
});
dropdown.appendChild(item);
});
document.body.appendChild(dropdown);
}
function insertUsername(username) {
const inputElement = document.getElementById('commentInput');
const text = inputElement.value;
const atIndex = text.lastIndexOf('@');
inputElement.value = text.slice(0, atIndex) + '@' + username + ' ';
inputElement.focus();
}
</script>
</body>
</html>
注意事项
- 确保用户列表下拉框的位置正确,可能需要根据输入框的位置动态计算。
- 考虑添加键盘导航功能,允许用户使用上下箭头选择用户名。
- 在实际应用中,用户列表可能来自后端API,需使用异步请求获取数据。






