前端实现tooltip

kyaa111 1月前 ⋅ 44 阅读

鼠标悬浮在问号图标上, 下方展示提示文本.

.tooltip {
    margin: 8px;
    padding: 8px;
    border: 1px solid #CCCCCC;
    background-color: #F6DBB3;
    position: absolute;
    z-index: 2;
}

.arrow-div {
    position: absolute;
    z-index: 3;
    display: inline-block;
    border-top: 1px solid;
    border-right: 1px solid;
    width: 8px;
    height: 8px;
    border-color: #CCCCCC;
    transform: rotate(-45deg);
    margin: 50px auto auto 100px;
    background-color: #F6DBB3;
}
<i class="fa fa-question-circle-o" id="helpIcon" style="font-size: 24px; color: #D0CFCF; margin-left: 13px;"></i>
let changeTooltipPosition = function (event) {
    let xy = $('#helpIcon').offset();
    let tooltipX = xy.left - 180;
    let tooltipY = xy.top + 35;
    $('div.tooltip').css({top: tooltipY, left: tooltipX});
    $('div.arrow-div').css({top: tooltipY - 47, left: tooltipX + 87});
};

let showTooltip = function(event) {
    let div = `<div class="arrow-div"></div><div class="tooltip">提示文本</div>`

    $('div.tooltip').remove();
    $('div.arrow-div').remove();
    $(div).appendTo('body');
    changeTooltipPosition(event);
};

let hideTooltip = function() {
    $('div.tooltip').remove();
    $('div.arrow-div').remove();
};


$("#helpIcon").bind({
    mousemove : changeTooltipPosition,
    mouseenter : showTooltip,
    mouseleave: hideTooltip
});