如何使用jquery获取基于指定高度的最近元素



我下面有一个HTML。我需要使用js在父div的中间插入一个图像或iframe。我的解决方案是,我将使用height((得到这个div的高度,然后将其除以2。之后,我需要根据高度找到壁橱p标签,然后将图像附加到该p标签上。在这种情况下,我如何根据高度获得壁橱p标签?

<div id="body-detail" class="body-detail">
<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<p>F</p>
</div>

  1. 获取父<div>的BoundingClientRect,计算其中间值
  2. 获取每个<p>的BoundingClientRect,计算其中间值
  3. 选择中间与<div>之间距离最小的<p>
  4. 将您的<img>附加到该<p>

注意在windowload事件中执行所有这些操作,这样可以保证<p>元素的大小已经确定,特别是如果它们包含没有固定大小的图像或在外部样式表中设置样式时。

$(window).on('load', _e => {
//TODO: remove (for tests only)
//Set random height for p elements
$('#body-detail p').each((index, p) => p.style.minHeight = (Math.random() * 50 + 20) + "px");
//Find parent div middle in height
const bodyDetail = $('#body-detail');
const bdRect = bodyDetail[0].getBoundingClientRect();
const bdMiddle = bdRect.y + bdRect.height / 2;
console.log('div middle at', bdMiddle);
//Find p which middle is the closest to parent div's
let closestP;
let closestDist = 1e9;
bodyDetail.children('p').each((index, p) => {
const pRect = p.getBoundingClientRect();
const pMiddle = pRect.y + pRect.height / 2;
console.log('  p middle at', bdMiddle);
const dist = Math.abs(pMiddle - bdMiddle);
if (dist < closestDist) {
console.log('  closer than', closestDist);
closestDist = dist;
closestP = $(p);
}
});
//Exit if none found
if (!closestP) {
console.log('No p in', bodyDetail);
return;
}
//Append image
closestP.append('<img src="https://picsum.photos/200/150" />');
closestP.addClass('appended');
});
.appended {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="body-detail" class="body-detail">
<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<p>F</p>
</div>

最新更新