萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Tooltip 插件:智慧定位、動畫與事件控制完整實作

插件功能特色

  • 四向智慧定位(上/下/左/右),自動偵測視窗邊界翻轉
  • 平滑動畫進場/退場,可配置距離、持續時間、透明度
  • 支援 `mouseover`/`mouseout`、`click`/`hover` 等觸發模式
  • 箭頭指示器自動對齊目標元素中心
  • 內容取自目標元素內部 ``,語意化結構

完整插件代碼(重構整理版)

(function($) {
    $.fn.tooltip = function(settings) {
        // 預設配置
        var config = {
            contentSelector: 'div.tooltip_description',
            animationDistance: 50,
            opacity: 0.85,
            arrowLeftOffset: 70,
            arrowTopOffset: 50,
            arrowHeight: 20,
            arrowWidth: 20,
            animationDuration: 300,
            eventIn: 'mouseover',
            eventOut: 'mouseout'
        };
        
        if (settings) $.extend(config, settings);
        
        // 主迴圈:為每個目標元素綁定事件
        return this.each(function() {
            var $target = $(this);
            
            $target.on(config.eventIn, function() { _show($target); })
                   .on(config.eventOut, function() { _hide($target); });
        });
        
        // 顯示邏輯
        function _show($target) {
            var $content = $target.find(config.contentSelector);
            if (!$content.length) return;
            
            var $box = _createBox($content);
            var pos = _calculatePosition($target, $box);
            
            // 定位箭頭
            $box.find(pos.arrowClass).css('top', 
                $box.outerHeight() - (config.arrowTopOffset * 2) + 'px');
            
            // 動畫進場
            $box.css(pos.start).animate(pos.end, config.animationDuration);
        }
        
        // 隱藏邏輯
        function _hide($target) {
            $('.tooltip_box').fadeOut(config.animationDuration, function() {
                $(this).remove();
            });
        }
        
        // 建立 tooltip DOM
        function _createBox($content) {
            var html = '<div class="tooltip_box" style="position:absolute;z-index:9999;opacity:0">'
                     + '<div class="tooltip_content">' + $content.html() + '</div>'
                     + '<div class="arrow up_arrow"></div>'
                     + '<div class="arrow down_arrow"></div>'
                     + '<div class="arrow left_arrow"></div>'
                     + '<div class="arrow right_arrow"></div>'
                     + '</div>';
            return $(html).appendTo('body');
        }
        
        // 智慧定位核心演算法
        function _calculatePosition($target, $box) {
            var tp = $target.offset();
            var th = $target.outerHeight();
            var tw = $target.outerWidth();
            var bh = $box.outerHeight();
            var bw = $box.outerWidth();
            var vp = { w: $(window).width(), h: $(window).height() };
            var scroll = { l: $(window).scrollLeft(), t: $(window).scrollTop() };
            
            // 預設:右側
            var pos = {
                start: { left: tp.left + tw + config.animationDistance, top: tp.top + th/2 - config.arrowTopOffset },
                end:   { left: tp.left + tw,                       top: tp.top + th/2 - config.arrowTopOffset },
                arrowClass: 'div.left_arrow'
            };
            
            // 空間不足時翻轉邏輯(簡化版)
            if (tp.left + tw + bw + config.animationDistance > vp.w + scroll.l) {
                // 右側空間不足 → 顯示在左側
                pos = {
                    start: { left: tp.left - bw - config.animationDistance, top: tp.top + th/2 - config.arrowTopOffset },
                    end:   { left: tp.left - bw,                       top: tp.top + th/2 - config.arrowTopOffset },
                    arrowClass: 'div.right_arrow'
                };
            } else if (tp.top + th + bh + config.animationDistance > vp.h + scroll.t) {
                // 底部空間不足 → 顯示在上方
                pos = {
                    start: { left: tp.left + tw/2 - config.arrowLeftOffset, top: tp.top - bh - config.animationDistance },
                    end:   { left: tp.left + tw/2 - config.arrowLeftOffset, top: tp.top - bh + config.arrowHeight },
                    arrowClass: 'div.down_arrow'
                };
            }
            // ... 可繼續擴展上方/左方邏輯
            
            return pos;
        }
    };
})(jQuery);

HTML 結構範例

<div class="tooltiptopright">
    懸停我
    <div class="tooltip_description" style="display:none">
        <h4>提示標題</h4>
        <p>這是詳細說明內容,支援任意 HTML。</p>
    </div>
</div>

<script>
$(function() {
    $('.tooltiptopright, .tooltipbottom, .tooltipbottomright').tooltip({
        eventIn: 'mouseover',
        eventOut: 'mouseout',
        animationDuration: 200
    });
});
</script>

CSS 樣式建議

.tooltip_box {
    background: #333;
    color: #fff;
    padding: 12px 16px;
    border-radius: 6px;
    font-size: 14px;
    line-height: 1.5;
    max-width: 300px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}

.tooltip_box .arrow {
    position: absolute;
    width: 0; height: 0;
    border: 8px solid transparent;
}

.tooltip_box .up_arrow    { bottom: -16px; left: 50%; margin-left: -8px; border-top-color: #333; }
.tooltip_box .down_arrow  { top: -16px;   left: 50%; margin-left: -8px; border-bottom-color: #333; }
.tooltip_box .left_arrow  { right: -16px; top: 50%;  margin-top: -8px;  border-left-color: #333; }
.tooltip_box .right_arrow { left: -16px;  top: 50%;  margin-top: -8px;  border-right-color: #333; }

優化建議

  1. 防抖動:`mouseover`/`mouseout` 易誤觸發,加入 `setTimeout` 延遲顯示/隱藏
  2. 點擊外部關閉:`$(document).on('click', function(e) { if (!$(e.target).closest('.tooltip_box, [data-tooltip]').length) hideAll(); })`
  3. 滾動/縮放重定位:監聽 `scroll`/`resize` 事件更新位置
  4. 無障礙:`role="tooltip"`、`aria-describedby` 關聯
  5. 銷毀方法:提供 `$(...).tooltip('destroy')` 移除事件與 DOM

現代替代:Popper.js / Floating UI

生產環境強烈建議使用 Floating UI(原 Popper.js):

import { computePosition, flip, shift, offset, arrow } from '@floating-ui/dom';

const tooltip = document.getElementById('tooltip');
const trigger = document.getElementById('trigger');

computePosition(trigger, tooltip, {
    placement: 'top',
    middleware: [offset(8), flip(), shift({ padding: 8 }), arrow({ element: arrowEl })]
}).then(({ x, y, placement, middlewareData }) => {
    Object.assign(tooltip.style, { left: x + 'px', top: y + 'px' });
    // 箭頭定位
    const { x: arrowX, y: arrowY } = middlewareData.arrow;
    Object.assign(arrowEl.style, { left: arrowX + 'px', top: arrowY + 'px' });
});
copyright © 萬盛學電腦網 all rights reserved