js实现评论发送表情
实现评论发送表情的步骤
准备工作 确保HTML中有一个评论输入框和一个表情选择面板。表情可以用Unicode字符或图片表示。
HTML结构示例
<div class="comment-box">
<textarea id="comment-input" placeholder="输入评论..."></textarea>
<div class="emoji-panel">
<span class="emoji" data-emoji="😀">😀</span>
<span class="emoji" data-emoji="😂">😂</span>
<!-- 更多表情 -->
</div>
<button id="submit-comment">发送</button>
</div>
JavaScript实现 监听表情点击事件,将选中表情插入到输入框光标位置。

document.querySelectorAll('.emoji').forEach(emoji => {
emoji.addEventListener('click', function() {
const input = document.getElementById('comment-input');
const cursorPos = input.selectionStart;
const emojiChar = this.getAttribute('data-emoji');
input.value = input.value.substring(0, cursorPos) +
emojiChar +
input.value.substring(cursorPos);
input.focus();
input.setSelectionRange(cursorPos + emojiChar.length, cursorPos + emojiChar.length);
});
});
存储和显示评论 当用户提交评论时,将内容保存并显示在页面上。
document.getElementById('submit-comment').addEventListener('click', function() {
const comment = document.getElementById('comment-input').value;
if (comment.trim()) {
const commentList = document.createElement('div');
commentList.className = 'comment';
commentList.textContent = comment;
document.body.appendChild(commentList);
document.getElementById('comment-input').value = '';
}
});
增强功能建议
使用表情图片 如果不想用Unicode字符,可以使用图片作为表情。

<span class="emoji" data-emoji=":smile:">
<img src="smile.png" alt="smile">
</span>
表情面板切换 添加按钮控制表情面板的显示/隐藏。
document.getElementById('toggle-emoji').addEventListener('click', function() {
const panel = document.querySelector('.emoji-panel');
panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
});
移动端优化 对于移动设备,可以考虑使用系统自带的表情键盘。
document.getElementById('comment-input').addEventListener('focus', function() {
this.setAttribute('inputmode', 'emoji');
});






