直接使用原生 JavaScript 或 jQuery 方法获取元素的包含块 [英] Direct native JavaScript or jQuery method to get containing block of an element

查看:23
本文介绍了直接使用原生 JavaScript 或 jQuery 方法获取元素的包含块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有内置的 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时起作用、relativefixed,但它也适用于我的 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屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆