问题描述
限时送ChatGPT账号..是否有内置的 DOM API 或 jquery API 来获取 包含元素的块?
我不是在问如何获取元素的包含块.我只是问是否已经有了轮子,所以我不必重新发明它.如果没有,我可以这样做:
let containsBlock = $("#five").父母().find(parent => parent.css("position") === ...);
对于以下 HTML,例如:
<div id = "two" style = "position: absolute;"><div id = "三个"><div id = "四"><div id = "5" style = "position: absolute;"></div>
解决方案 您可以使用 offsetParent()
来获取被定位的最近的父元素.根据文档,它在父元素定位absolute
时起作用、relative
或 fixed
,但它也适用于我的 sticky
定位.
Is there a built-in DOM API or a jquery one to get the containing block of an element?
I am not asking how to get the containing block of an element. I am just asking if there's already the wheel so I don't have to re-invent it. If there isn't, I could just do:
let containingBlock = $("#five")
.parents()
.find(parent => parent.css("position") === ...);
for the following HTML, for example:
<div id = "one">
<div id = "two" style = "position: absolute;">
<div id = "three">
<div id = "four">
<div id = "five" style = "position: absolute;"></div>
</div>
</div>
</div>
</div>
解决方案
You can use offsetParent()
to get the closest parent element that is positioned. According to the documentation, it works when the parent element is positioned absolute
, relative
, or fixed
, but it also worked with sticky
positioning for me.
这篇关于直接使用原生 JavaScript 或 jQuery 方法获取元素的包含块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论