如何通过给定的clientHeight在选定的<p>元素之前/之后附加一个<div>?

时间:2019-04-09 17:35:31

标签: javascript html vue.js

我在给定div的{​​{1}}元素之前添加paragraph时遇到问题。在这种情况下,我想从给定的clientHeight中获取最接近的paragraph,并在该元素之后/之前添加一个clientHeight

这里是示例:

div

我想从<div id="content"> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <p>Paragraph 4</p> <p>Paragraph 5</p> </div> clientHeight中获取最接近的<p>,然后添加一个30px

我该怎么做?

2 个答案:

答案 0 :(得分:1)

获取所有P,并找到最接近的

let myPs = document.querySelectorAll("P");
if (myPs.length == 0) //handle this error case
else {
  var bestP, bestDist;
  bestP = myPs[0];
  bestDist = ... // calculate the minimum distance from either y or y + height to `clientHeight` for myPs[0]
  for (let i = 1; i < myPs.length; i++) {
    // compare distance as about to bestDist. If less, replace bestDist and bestP
  }
}

答案 1 :(得分:0)

比较子项的offsetTop与父项的offsetTop

const addDividers = (el) => {
  ['beforebegin', 'afterend'].forEach(pos => {
    const div = document.createElement('div');
    div.textContent = 'DIVIDER';
    el.insertAdjacentElement(pos, div);
  });
}

const cont = document.getElementById('content'),
  wanted = Array.from(cont.children).find(el => el.offsetTop >= cont.offsetTop+ 30 );

if (wanted) {
  addDividers(wanted)
}
<div id="content">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
  <p>Paragraph 4</p>
  <p>Paragraph 5</p>
</div>