【发布时间】:2021-03-29 18:03:39
【问题描述】:
我有一个博客文章页面,其中有一个名为 PostContent 的组件,其中包含文章的文本。我想要实现的是根据其长度在此PostContent 的段落中动态添加一些内容。我将通过以 1.5 倍视口高度的距离引入上述内容来做到这一点。
我的问题是我无法计算距离。我正在使用https://www.npmjs.com/package/html-react-parser,但我无法使用它访问 DOM 元素的offsetHeight 属性,我想知道元素与容器元素顶部的距离。
有没有更好/替代的方法来实现我想要的?
谢谢!
假设视口高度为 100px,帖子内容为 2000px,所以我想每 200px(2x 视口高度)添加一个元素。
<article>
<p>This is the first example paragraph of 10px</p>
<p>This is the second example paragraph of 10px</p>
// ...
<p>This is the twentieth example paragraph of 10px</p>
// ...
</article>
为此,我需要遍历article 的所有段落,以便访问每个段落的offsetHeight。这样,我就会知道我离容器有多远。因此,我总是添加想要的元素,即 offsetHeight 是 200px 的倍数,对吧?
<article>
<p>This is the first example paragraph of 10px</p>
<p>This is the second example paragraph of 10px</p>
// ...
<p>This is the twentieth example paragraph of 10px</p>
<!-- Here I would insert the first element,
as it would be at 200px from the container (article).
-->
// .... same applies with the rest of the article ....
</article>
【问题讨论】:
标签: javascript html reactjs dom