如何使用javascript获取我们知道其顶部偏移量的元素

假设我们知道特定元素的顶部偏移量,并且想要获取位于该点的元素,那么有什么方法可以获取它吗?


例如,我们有 DOM 元素,其偏移量 top = 6000,我们想要找到位于该偏移量顶部的元素。


例子:


  <ul>

     <li>first list</li>

     <li>second list</li>

     <li>third list</li>

  </ul>

  <h3>Skills:</h3>

      <p>This are my skills. xyz, abc, pqr</p>

现在,假设元素的offsetTop为10,我们希望整个元素的含义类似于,只需使用它的 offsetTop 即可。<p> <p>This are my skills. xyz, abc, pqr</p>


动漫人物
浏览 63回答 1
1回答

扬帆大鱼

对我来说,问题似乎是寻找特定点的元素。如果是这样你可以使用document.elementFromPoint().let x = 10;let y = 140;let el = document.elementFromPoint(x, y);el.style.background = "red";// or $(el).css("background", "red");<ul>   <li>first list</li>   <li>second list</li>   <li>third list</li></ul><h3>Skills:</h3><p>This are my skills. xyz, abc, pqr</p>如果您只想通过顶部偏移量,例如因为您不想指定坐标x,则必须遍历您的元素。红线显示要检查的顶部偏移。添加并返回该行之前和之后的所有元素。它们以蓝色背景显示。/** * Get all children that start before `offset_top` and end after  * `offset_top`. * * @param {(HTMLElement|jQuery|string)} parent  *    The parent as the element or as the selector * @param {number} offset_top *    The top offset to check * * @return {jQuery} *    All elements that are on the specific location. */function findChildrenWithOffset(parent, offset_top){  let found = $([]);  $(parent).children().each(function(){    let t = $(this);    let o = t.offset();    let start = o["top"];    let end = start + t.outerHeight();    if(start <= offset_top && offset_top <= end){      found = found.add(t);    }    if(t.children().length > 0){      t.children().each(function(){        found = found.add(findChildrenWithOffset(this, offset_top));      });    }  });    return found;}let c = findChildrenWithOffset(document, 140);$(c).css("background", "rgba(0, 0, 255, 0.2)");.absolute{  position: absolute;  height: 20px;  width: 20px;  border: 1px solid green;}.offset-line{  position: absolute;  top: 139px;  left: 0;  right: 0;  background: red!important;  height: 2px;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><ul>   <li>first list</li>   <li>second list</li>   <li>third list</li></ul><h3>Skills:</h3><p><span style="text-decoration: underline;">This</span> are my skills. xyz, abc, pqr</p><div class="absolute" style="left: 220px; top: 110px;">  A1</div><div class="absolute" style="left: 240px; top: 120px;">  A2</div><div class="absolute" style="left: 260px; top: 130px;">  A3</div><div class="absolute" style="left: 280px; top: 140px;">  A4</div><div class="absolute" style="left: 300px; top: 150px;">  A5</div><div class="offset-line"></div>

慕侠2389804

无法查询应用了特定样式的元素。您可以查询页面中的所有元素并循环遍历它们,检查它们的样式,但这会导致大量开销。不过,如果您可以根据父元素、类型等缩小可能的元素范围,那么这可能是可行的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript