You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何延长点击复制按钮后‘Copied!’提示文本的显示时长

解决点击后“Copied!”提示延长显示时长的问题

:active伪类仅在鼠标按钮按下期间生效,松开鼠标后立即失效,因此给它添加transition无法实现延长提示时长的需求。我们需要通过自定义CSS类配合JavaScript来控制提示的显示时长,具体修改如下:

修改后的CSS代码

.hexcodeStyle {
  font-size: 30px;
  font-weight: normal;
  margin-right: 15px;
  margin-left: 8px;
  text-align: center;
  background-color: white;
  position: relative;
  border: white solid 0;
  cursor: pointer; /* 增加指针样式,提示元素可点击 */
}

.hexcodeStyle:before {
  --scale: 0;
  position: absolute;
  top: -.25rem;
  left: 50%;
  padding: .3rem;
  width: max-content;
  background: lightgray;
  transform: translateX(-50%) translateY(-100%) scale(var(--scale));
  border-radius: .3rem;
  text-align: center;
  color: black;
  font-size: 12px;
  transition: transform 150ms ease; /* 明确指定过渡属性,优化动画流畅度 */
  transform-origin: bottom center;
}

.hexcodeStyle:hover::before {
  --scale: 1;
  content: 'Copy color';
}

/* 用自定义类替代:active,控制Copied提示的显示 */
.hexcodeStyle.copied::before {
  --scale: 1;
  content: 'Copied!';
}

修改后的JavaScript代码

function copyHex(celement) { 
  let hexCopy = celement.innerText;
  let input = document.createElement('input');
  input.setAttribute('value', hexCopy);
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
}

$(document).ready(function() {
  $('.hexcodeStyle').click(function() {
    const $currentElement = $(this);
    // 执行复制操作
    copyHex($currentElement[0]);
    // 添加copied类,显示Copied提示
    $currentElement.addClass('copied');
    // 2秒后移除类,隐藏提示
    setTimeout(function(){
      $currentElement.removeClass('copied');
    }, 2000);          
  });        
});

关键改动说明

  • 移除:active伪类规则,改用.copied自定义类触发“Copied!”提示,摆脱鼠标按压状态的限制
  • 明确transition的目标属性为transform,确保提示的显示/隐藏动画正常生效
  • 修正JavaScript中移除类的错误逻辑,直接操作当前点击的元素,避免无效选择器
  • 增加cursor: pointer样式,提升用户交互体验

内容的提问来源于stack exchange,提问作者J Gill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:35:22