在跨距上方放置高度可变的工具提示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>
);
};
解决方案
为了完成此操作,您需要设置工具提示元素的高度状态,然后相应地调整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表示从工具提示到单词的边距。
相关文章