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

选中文本时在选区底部居中显示‘Copied!’提示框的实现求助

Hey there! Let's fix this so your tooltip shows up centered at the bottom of the selected text. Here's a step-by-step solution using native JavaScript that works with your existing HTML and adjusted CSS:

Step 1: Adjust Your CSS

First, we'll modify the CSS to use a custom class (instead of :active) to toggle tooltip visibility, and switch to fixed positioning so we can place the tooltip exactly at the selection's bottom center using CSS variables.

[tooltip]{ 
  position:relative; 
  display:inline-block; 
} 

[tooltip]::before { 
  content: ""; 
  position: fixed; 
  left: var(--tooltip-x, 0); 
  top: var(--tooltip-y, 0); 
  transform: translateX(-50%) translateY(-100%); 
  border-width: 4px 6px 0 6px; 
  border-style: solid; 
  border-color: rgba(0,0,0,0.9) transparent transparent; 
  z-index: 99; 
  opacity:0; 
  transition: opacity 0.2s ease;
} 

[tooltip-position='bottom']::before{ 
  transform: translateX(-50%) translateY(0); /* Arrow points up towards the selection */
} 

[tooltip]::after { 
  content: attr(tooltip); 
  position: fixed; 
  left: var(--tooltip-x, 0); 
  top: var(--tooltip-y, 0); 
  transform: translateX(-50%) translateY(0); 
  background: rgba(0,0,0,0.9); 
  text-align: center; 
  color: #fff; 
  padding:4px 4px; 
  font-size: 12px; 
  min-width: 80px; 
  border-radius: 5px; 
  pointer-events: none; 
  z-index:99; 
  opacity:0; 
  transition: opacity 0.2s ease;
} 

/* Toggle visibility with this class */
[tooltip].show-tooltip::after,
[tooltip].show-tooltip::before { 
  opacity:1 
}

Step 2: Add Native JavaScript Logic

This code will listen for text selection events, check if the selection is within your .selectable element, copy the text to clipboard, and position/show the tooltip at the selection's bottom center.

document.addEventListener('selectionchange', handleSelection);

function handleSelection() {
  const selection = window.getSelection();
  const selectableEl = document.querySelector('.selectable');
  
  // Hide tooltip if no text is selected or selection is outside the target element
  document.querySelectorAll('[tooltip]').forEach(el => el.classList.remove('show-tooltip'));
  if (selection.isCollapsed) return;

  // Check if the selected text is inside the .selectable element
  const range = selection.getRangeAt(0);
  const isTargetSelected = selectableEl.contains(range.commonAncestorContainer);

  if (isTargetSelected) {
    const selectedText = selection.toString().trim();
    if (!selectedText) return; // Skip empty selections

    // Copy the selected text to clipboard
    navigator.clipboard.writeText(selectedText)
      .then(() => {
        // Get the bounding rectangle of the selected text
        const selectionRect = range.getBoundingClientRect();
        
        // Calculate tooltip position: center of selection, 8px below it
        const tooltipX = selectionRect.left + (selectionRect.width / 2);
        const tooltipY = selectionRect.bottom + 8;

        // Set CSS variables for tooltip position
        selectableEl.style.setProperty('--tooltip-x', `${tooltipX}px`);
        selectableEl.style.setProperty('--tooltip-y', `${tooltipY}px`);
        
        // Show the tooltip
        selectableEl.classList.add('show-tooltip');

        // Auto-hide tooltip after 2 seconds
        setTimeout(() => {
          selectableEl.classList.remove('show-tooltip');
        }, 2000);
      })
      .catch(err => {
        console.error('Failed to copy text:', err);
      });
  }
}

Step 3: Keep Your Existing HTML

No changes needed here—your original HTML works perfectly with this solution:

<p> 
  <span class="selectable" tooltip="Copied!" tooltip-position='bottom'> 
    Some lines of code 
  </span> 
</p>

How It Works

  1. Selection Detection: We use the selectionchange event to detect when the user selects text on the page.
  2. Validation: We check if the selection is within your .selectable element to avoid triggering the tooltip for other text.
  3. Copy to Clipboard: The navigator.clipboard.writeText() API copies the selected text (this aligns with the tooltip's "Copied!" message).
  4. Positioning: We calculate the exact bottom-center of the selected text using getBoundingClientRect() and set CSS variables to place the tooltip there.
  5. Auto-Hide: The tooltip automatically hides after 2 seconds for a clean, unobtrusive user experience.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:56:10