1

编写一个纯 JS 工具提示库,并使其工作得非常非常好。没有大的花里胡哨,只是一个超级轻量级​​、超级实用且易于定制的工具提示。也就是说,我在更新职位时遇到了问题;特别是当检测到工具提示超出范围时。

它有效!确实如此。问题是当我将鼠标悬停在目标元素上时,该元素位于页面右侧,导致工具提示超出范围,它将在默认的右下角位置和正确的左下角位置之间闪烁。经过进一步检查,它似乎只在我移动光标的所有其他头发上注册超出范围。例如,当我输入元素时,它会正常显示;向任何方向移动光标一根头发,它似乎会重置到右下角,而不是看到它超出了界限。将它再移动一根头发,它会再次发现它超出了界限,将自己纠正到左下角。我不确定在这里做出什么假设,但我会让你们来判断。

    updateTooltip(event) {
        const mouseX = event.pageX,
            mouseY = event.pageY;

        const adjustment = 15;

        let position = (this.element.getAttribute(this.selector + '-pos') || '').split(' ');

        if (position.length !== 2) position = [ 'bottom', 'right' ];

        var isOut = this.checkBounds();
        if (isOut.top)    { position[0] = 'bottom'; }
        if (isOut.left)   { position[1] = 'right'; }
        if (isOut.bottom) { position[0] = 'top'; }
        if (isOut.right)  { position[1] = 'left'; }

        let vertical, horizontal;

        switch (position[0]) {
            case 'top':
                vertical = -adjustment - this.tooltip.offsetHeight;
                break;
            case 'center':
                vertical = 0 - (this.tooltip.offsetHeight / 2);
                break;
            default:
                vertical = adjustment;
        }

        switch (position[1]) {
            case 'left':
                horizontal = -adjustment - this.tooltip.offsetWidth;
                break;
            case 'center':
                horizontal = 0 - (this.tooltip.offsetWidth / 2);
                break;
            default:
                horizontal = adjustment;
        }

        this.tooltip.style.top  = mouseY + vertical   + 'px';
        this.tooltip.style.left = mouseX + horizontal + 'px';
    }
    checkBounds() {
        if (!this.tooltip) return;

        const bounds = this.tooltip.getBoundingClientRect();

        let out = {};
        out.top = bounds.top < 0;
        out.left = bounds.left < 0;
        out.bottom = bounds.bottom > (window.innerHeight || document.documentElement.clientHeight);
        out.right = bounds.right > (window.innerWidth || document.documentElement.clientWidth);
        out.any = out.top || out.left || out.bottom || out.right;
        out.all = out.top && out.left && out.bottom && out.right;

        return out;
    }
4

0 回答 0