简体   繁体   中英

How to find out if an element is in a fixed positioned container?

Say I have a nested div layout where any div could have a fixed position (CSS position: fixed ):

<div class="MaybeIAmFixedToo">
    <div>
        <div class="MaybeIAmFixed">
            <div>
                <div id="IAmTheTarget">I am the target</div>
            </div>
        </div>
    </div>
</div>

I have a jQuery reference of the innermost element: $('#IAmTheTarget') .

How can I (at best, without creating a performance nightmare :)) find out if my target is in a fixed positioned container? For example, $('.MaybeIAmFixed') could have a fixed position, but so could also any other parent of my target.

Edit: I need to know this because when the element is fixed, I need to get its position with $('#IAmTheTarget').position(); and if not, I need to get it with $('#IAmTheTarget').offset();

You can't via any kind of simple selector. You could filter the element's parent list based on position, though:

var fixedp = $('#IAmTheTarget').parents().filter(
  function() {
    return $(this).css('position') == 'fixed';
  }
);

alert('fixed ancestors? ' + (fixedp.length ? "yes" : "no"));

Example: http://codepen.io/paulroub/pen/axrFB

Here is an implementation of the function Paul was mentioning, stopping at the first parent that is fixed :

function isElementFixed(el) {
    var $el = $(el);
    while (!$el.is(document)) {
        if ($el.css("position") === "fixed") {
            return true;
        }
        $el = $el.parent();
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM