位置工具提示 div 与跨度上方的可变高度(反应)

时间:2021-07-28 13:53:29

标签: javascript html css reactjs styled-components

我正在尝试构建一个显示在某些文本中的单词上方的工具提示。如果工具提示 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>
    );
};

1 个答案:

答案 0 :(得分:0)

为了实现这一点,您需要为工具提示元素的高度设置状态,然后相应地调整 top css 属性。像这样的事情会起作用:

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 代表从工具提示到单词的边距。

相关问题