本文将介绍如何在 addMessage 方法中创建每一个气泡里面增加一个复制按钮。复制按钮在气泡文字前面。复制功能适配安卓浏览器。再美化一下复制按钮。

注意 lastMessageContainer.querySelector('.message-bubble').innerText += messageText; 这里内容:是将消息文本添加到气泡中的方法,需要将复制按钮插入到气泡文本前面。

具体实现如下:

  1. addMessage 方法中,在创建气泡的代码后面添加以下代码:
// 创建复制按钮
var copyBtn = document.createElement('button');
copyBtn.className = 'copy-button';
copyBtn.innerHTML = '<i class="fas fa-copy"></i>';

// 将复制按钮插入到气泡文本前面
bubble.appendChild(copyBtn);
bubble.insertBefore(copyBtn, bubble.firstChild);
  1. 在 CSS 中添加以下样式来美化复制按钮:
.copy-button {
  position: absolute;
  top: 50%;
  left: -32px;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  border: none;
  background-color: transparent;
  color: #b3b3b3;
  cursor: pointer;
}

.copy-button:hover {
  color: #555;
}

.copy-button i {
  font-size: 14px;
}
  1. 在复制按钮被点击时,获取气泡文本并将其复制到剪贴板中:
document.addEventListener('click', function(event) {
  if (event.target.classList.contains('copy-button')) {
    var bubble = event.target.parentElement;
    var message = bubble.querySelector('.message-bubble');
    var range = document.createRange();
    range.selectNodeContents(message);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand('copy');
    selection.removeAllRanges();
  }
});

通过以上步骤,你就可以在聊天气泡中添加一个复制按钮,实现安卓浏览器兼容,并美化按钮样式。

在气泡中添加复制按钮:适配安卓浏览器并美化按钮

原文地址: https://www.cveoy.top/t/topic/mZBC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录