在跨距上方放置高度可变的工具提示div(反应) [英] Position Tooltip div with variable height above span (React)

查看:25
本文介绍了在跨距上方放置高度可变的工具提示div(反应)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个显示在某些文本中的单词上方的工具提示。如果工具提示div始终具有相同的高度,则可以很好地工作。但有时我希望里面有一大堆文本或其他东西,有时可能是一个单行句子。

我被困在如何在这里编码定位,因为我需要工具提示的高度?我希望工具提示div始终居中于目标单词上方,并且工具提示宽度和高度完全可变,并且绝不与目标单词重叠。

到目前为止,我得到的是:

const wordWithToolTip = ({ word, tooltip }) => {

    return (
        <div
            style={{ display: 'inline-block', position: 'relative', border: '2px solid red' }}
            
            onMouseEnter={() => setShowTranslation(true)}
            onMouseLeave={() => setShowTranslation(false)}>

            {showTranslation && (
                <div
                    style={{
                        position: 'absolute',
                        top: '-30px', //this works fine, but I cannot assume that 30px will always suffice. If the tooltip div gets really big, -30px won't do anything and it will overlap the word and look off. Ideally, I'd have something that says: always appear 10px above the word, and go as high as you want, but never below those 10px etc.
                        padding: '2px',
                        border: '2px solid black',
                        backgroundColor: 'white',
                    }}>
                    {tooltip}
                </div>
            )}
            <span>{word}</span>
        </div>
    );
};

推荐答案

为了完成此操作,您需要设置工具提示元素的高度状态,然后相应地调整topcss属性。这样做会奏效的:

const wordWithToolTip = ({ word, tooltip }) => {

const [height, setHeight] = useState("");
const tooltipEl = useRef(null);

useEffect(() => {
   const refheight = tooltipEl.current.offsetHeight;
   setHeight({ refheight });
}, []);

return (
    <div
        style={{ display: 'inline-block', position: 'relative', border: '2px solid red' }}
        
        onMouseEnter={() => setShowTranslation(true)}
        onMouseLeave={() => setShowTranslation(false)}>

        {showTranslation && (
            <div
                ref={tooltip}
                style={{
                    position: 'absolute',
                    top: '-' + height+10 + 'px', //You'll have to adjust this accordingly. 
                    padding: '2px',
                    border: '2px solid black',
                    backgroundColor: 'white',
                }}>
                {tooltip}
            </div>
        )}
        <span>{word}</span>
    </div>
);
};

10表示从工具提示到单词的边距。

这篇关于在跨距上方放置高度可变的工具提示div(反应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆