直接使用原生 JavaScript 或 jQuery 方法获取元素的包含块

编程入门 行业动态 更新时间:2024-10-27 04:34:39
本文介绍了直接使用原生 JavaScript 或 jQuery 方法获取元素的包含块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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时起作用、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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-23 08:36:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1038488.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   方法   JavaScript   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!