交叉口观察者不能使用位置:固定的目标 [英] Intersection observer does not work with target with position: fixed

查看:64
本文介绍了交叉口观察者不能使用位置:固定的目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过交集观察者调用回调。

I am trying to invoke a callback via intersection observer.

我希望目标样式:position:fixed并通过
style.top 移动它。

I want the target to be style: "position: fixed" and move it via style.top.

我还用 style指定了根元素,它是目标的祖先:position:relative

但是当目标和观察者相交时,回调函数不会被触发。

But when the target and the observer intersects, the callback function won't be triggered.

是否有我错过了一些限制?

Are there some limitations I missed?

这是我输入的内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>IO</title>
</head>
<body>
<div style="height: 200px;width: 100%;background: violet" class="upper">aaa</div>
<div style="position:relative;height: 200px;width: 100%;background: blueviolet" id="middle">bbb
    <div id="target" style="position:fixed;top: 0px;width: 50px;height: 50px;background: firebrick">ccc</div>
</div>
<script>
    let options = {
        root: document.getElementById("middle"),
        rootMargin: '0px',
        threshold: 0
    };
    let observer = new IntersectionObserver(entry => {
        console.log("observer's acting.")
    }, options);

    let target = document.getElementById("target");
    observer.observe(target);

    let stepping = 0;

    let cb = () => {
        target.style.top = stepping + 'px';
        stepping += 4;
        if (stepping < 300){
            setTimeout(cb, 100);
        }
    };

    window.addEventListener("click", () => {
        cb();
    })
</script>
</body>
</html>

这是一个codepen演示:
codepen demo

And here is a codepen demo: codepen demo

您可以点击页面中的任意位置开始移动 ccc 阻止。

You can click anywhere in the page to start moving the ccc block.

推荐答案

元素 position:fixed 相对于视口定位,视口移动。因此,当您滚动时,固定定位元素会移动。即使 #target #middle 的孩子,我相信IntersectionObserver,无论它在引擎盖下使用什么计算目标是否进入/离开 root ,从不触发回调,因为目标在文档流程之外。

Elements with position: fixed are positioned relative to the viewport and the viewport moves. So, fixed positioned elements "move" as you scroll. Even though #target is a child of #middle, I believe the IntersectionObserver, with whatever it uses under the hood to calculate if the target is entering/leaving the root, never fires the callback because the target is outside of the document flow.

这是一个相关问题。与此问题相关的互联网中没有太多内容: https: //bugs.chromium.org/p/chromium/issues/detail?id=653240

Here is a related issue. There isn't much out in the interwebs related to this issue: https://bugs.chromium.org/p/chromium/issues/detail?id=653240

注意:设置 position:absolute目标确实在进入和离开视口时触发了回调。

Note: Setting position: absolute on the target does indeed fire the callback when entering and leaving the viewport.

这篇关于交叉口观察者不能使用位置:固定的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆