标签: intersection-observer

IntersectionObserver rootMargin 的正负值不起作用

设置的代码rootMargin如下所示。

let observerOptions = {
    root: null,
    rootMargin: "100px",
    threshold: []
};
Run Code Online (Sandbox Code Playgroud)

当我将其设置为 时100px,根元素的边界框不会增长 100 像素;当我将其设置为 时-100px,根元素的边界框不会缩小 100 像素。

这是一个关于 jsFiddle例子。该示例直接取自MDN 的 IntersectionObserver 文档,我只更改了rootMargin.

javascript intersection-observer

5
推荐指数
1
解决办法
4776
查看次数

如何检测元素可见性(z-index、fixed、opacity 等)(Intersection Observer V2 替代方案)

Intersection Observer V2 将引入新功能,以根据不透明度、z-index 和固定定位等因素检测实际能见度。

信息:https : //developers.google.com/web/updates/2019/02/intersectionobserver-v2

问题:是否有替代方法或 polyfill 来检测在当前浏览器中有效的实际可见性?

测试:https : //jsfiddle.net/v3kgewhf/

// Intersection Observer V2
const observer = new IntersectionObserver((changes) => {
  for (const change of changes) {
    // ?? Feature detection
    if (typeof change.isVisible === 'undefined') {
      // The browser doesn't support Intersection Observer v2, falling back to v1 behavior.
      change.isVisible = true;
    }
    if (change.isIntersecting && change.isVisible) {
      visibleSince = change.time;
    } else {
      visibleSince = 0;
    }
  }
}, {
  threshold: [1.0], …
Run Code Online (Sandbox Code Playgroud)

javascript visibility z-index intersection-observer

5
推荐指数
1
解决办法
625
查看次数

当达到 50% 视口高度时,使用 IntersectionObserver 和 rootMargin 进行更改

我完全被交叉点观察者的rootMargin属性弄糊涂了。

我的目标是在元素的一半高度穿过视口的垂直中心时向元素添加一个类。

期望结果图

在我当前的项目中,我所做的一切似乎都不会影响“根交叉矩形”,并且总是立即添加该类。我已经在最新的 Chrome 和 Firefox 中进行了测试。

这是简化的测试用例:

// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

const options = {
  root: null, // default, use viewport
  rootMargin: '0px 0px -50% 0px',
  threshold: 0.5 // half of item height
}

const circle = document.getElementById('circle');

const observerCallback = function(entries, observer) {
  console.log('intersected');
  circle.classList.add('intersected');
}

window.addEventListener('load', function(event) {

  const observer = new IntersectionObserver(observerCallback, options);

  observer.observe(circle);

}, false);
Run Code Online (Sandbox Code Playgroud)
.circle {
  margin: 100vh auto;
  width: 200px;
  height: 200px;
  background-color: tomato;
  border-radius: 50%;
  transition: background-color 2s ease-in-out;
}

.circle.intersected …
Run Code Online (Sandbox Code Playgroud)

intersection-observer

5
推荐指数
1
解决办法
8142
查看次数

IntersectionObserver:rootMargin 如何工作?

当目标元素距离交集根 100px 时,我想截取一个交集

在此处输入图片说明

为了做到这一点,我已经将 rootMargin 设置为“100px 0px 100px 0px”。

在这个例子中,当目标元素(红色框)的第一个像素进入交集根时,交集就变成了

在此处输入图片说明

我希望当目标元素距交叉根(灰色区域)100px 时,intersetion 变为

    var io = new IntersectionObserver(function(entries){
      document.getElementById('info').innerHTML =  entries[0].isIntersecting ? 'isIntersecting = true' : 'isIntersecting = false'; 
    }, {
      rootMargin: '100px 0px 100px 0px'
    });
    io.observe(document.getElementById('target'));
Run Code Online (Sandbox Code Playgroud)
* {
  padding: 0;
  margin: 0;
}

.pad {
  height: 1000px;
}

#target {
  background: rgb(237, 28, 36);
  height: 100px;
  outline: 100px solid rgba(0,0,0,0.2);
}

#info {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 2rem;
}
Run Code Online (Sandbox Code Playgroud)
<div class="pad"></div>
<div …
Run Code Online (Sandbox Code Playgroud)

javascript intersection-observer

5
推荐指数
1
解决办法
4960
查看次数

Gatsby - IntersectionObserver 未定义

我正在尝试构建我的 gatsby 项目,但由于 IntersectionObserver 未被识别,我无法构建。我在 InView 组件中使用了intersectionObserver:

import React, { useRef, useState, useEffect } from 'react'


const InView = ({ children }) => {
    const [boundingClientY, setBoundingClientY] = useState(null)
    const [direction, setDirection] = useState(null)
    const [element, setElement] = useState(null)
    const [inView, setInView] = useState(false)



    const observer = useRef(new IntersectionObserver((entries) => {
        const first = entries[0]
        const { boundingClientRect } = first
        first.isIntersecting && setInView(true)
        !first.isIntersecting && setInView(false)
        boundingClientRect.y > boundingClientY && setDirection('down')
        boundingClientRect.y < boundingClientY && setDirection('up')
        boundingClientY && setBoundingClientY(first.boundingClientRect.y) …
Run Code Online (Sandbox Code Playgroud)

polyfills reactjs gatsby intersection-observer

5
推荐指数
1
解决办法
5119
查看次数

就视口而言,Intersection Observer 是否在跨域 iframe 内部工作?

有没有办法从跨域 iframe 内部确定 iframe 是否在视图中?我试图使用 Intersection Observer API 来实现这一点。但它似乎仅适用于同域 iframe 而不适用于跨域。我检查了 Intersection Observer API 文档(在MDNW3C 上),但找不到与此相关的任何内容。我希望我在这里没有遗漏任何东西。

这是示例代码

主 HTML 页面

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Main Page</title>
</head>

<body>
    <div style="margin:700px auto;text-align:center;">
        <iframe marginwidth="0" marginheight="0" frameborder="0" height="250px" width="300px"
            id="aax_if_aax_sidebar-btf-1" allowtransparency="true" src="http://127.0.0.1:8080/iframe.html"></iframe>
    </div>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

嵌入式 iframe 页面

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Iframe</title>
</head>

<body>
    <div id="abc" style="background-color: black;width:100%;height: 100%;"></div>
    <script>
        setupIntersectionObserver = function (adContainer) {
            console.log('setting up observer', observer);
            var observer = new IntersectionObserver(
                function …
Run Code Online (Sandbox Code Playgroud)

html javascript google-chrome intersection-observer

5
推荐指数
1
解决办法
1005
查看次数

vue.js 中 Intersection Observer 的问题

这是我第一次使用 IntersectionObserver 并且我遵循了这个文档https://www.netguru.com/codestories/infinite-scroll-with-vue.js-and-intersection-observer 。但是我因为这个错误被屏蔽了

[Vue warn]: Error in mounted hook: "TypeError: Failed to construct 'IntersectionObserver': The provided value is not of type '(Element or Document)'"
Run Code Online (Sandbox Code Playgroud)

这是我的触发器组件

<template>
  <span ref='trigger'></span>
</template>

<script>
export default {
  props:{
    options:{
      type: Object,
      default: () => ({
        root: 0,
        threshold: "0",
      })
    }
  },
  data(){
    return{
      observer : null
    }
  },
  mounted(){
    this.observer = new IntersectionObserver( entries => {
      this.handleIntersect(entries[0]);
    }, this.options);

    this.observer.observe(this.$refs.trigger);
  },
  destroyed(){
    this.observer.disconnect();
  },
  methods:{
    handleIntersect(entry){
      if (entry.isIntersecting) this.$emit("triggerIntersected");
    }
  } …
Run Code Online (Sandbox Code Playgroud)

javascript vue.js vue-component intersection-observer

5
推荐指数
1
解决办法
1896
查看次数

IntersectionObserver 在 Safari 或 iOS 中不起作用

我有一段代码,根据元素是从顶部还是底部滚动进入或退出视口,向元素添加不同的 css 类。

它使用Intersection Observer是因为它应该比scroll事件更好地处理大量元素。

但是,我在使用此代码时遇到了两个问题:

  1. 它在 Safari(最新版本)中不起作用
  2. 它不适用于移动 Apple 设备

这很奇怪,因为 IntersectionObserver 应该可以在 Safari 甚至 iOS 上的移动浏览器上正常工作。

您可以在 jsFiddle 上找到代码或在此处查看代码段:

const config = {
  // Add root here so rootBounds in entry object is not null
  root: document,
  // Margin to when element should take action
  rootMargin: '-50px 0px',
  // Callback will be fired 30 times during intersection 
  threshold: [...Array(30).keys()].map(x => x / 29)
};

let observer = new IntersectionObserver(function(entries, observer) {

  entries.forEach((entry, …
Run Code Online (Sandbox Code Playgroud)

javascript jquery intersection-observer

5
推荐指数
2
解决办法
4529
查看次数

未捕获的类型错误:无法在“IntersectionObserver”上执行“observe”:参数 1 不是“元素”类型

我正在 Intersection Observer 上观看视频,我已经逐字复制了他的脚本,但不知何故我收到了这个错误。有人遇到了同样的错误,但通过将 querySelectorAll 更改为 querySelector 解决了他们的问题。即使我复制了他们的代码并将其更改为 querySelector,它仍然无法正常工作。下面的代码是我的。我正在使用 vs 代码实时服务器。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel='stylesheet' href='style.css'>
    <script src='script.js'></script>
</head>
<body>
    <section class = 'section1'></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
const sectionOne = document.querySelector('.section1');

const options = {};

const observer = new IntersectionObserver(function
(entries, observer){
    entries.forEach(entry => {
        console.log(entry);
    });
}, options);

observer.observe(sectionOne);
Run Code Online (Sandbox Code Playgroud)
body{
    padding: 0;
    margin: 0;
}

section{
    height: 100vh;
    width:100%;
}
section:nth-child(odd){
    background: lightcoral
}
Run Code Online (Sandbox Code Playgroud)

javascript intersection-observer

5
推荐指数
1
解决办法
1万
查看次数

在codepen中,Intersection观察者与浏览器窗口有不同的行为

如果我在单独的 HTML、CSS 和 Javascript 文件中编写此代码并使用浏览器打开它,则当在视口高度中间观察到的目标时,会出现粘性共享栏,而当在视口高度的底部观察到的目标时,会在 codepen 中出现。是什么原因?

{
    class StickyShareBar {
        constructor(element) {
            this.element = element;
            this.contentTarget = document.getElementsByClassName('js-sticky-sharebar-target');
            this.showClass = 'sticky-sharebar--on-target';
            this.threshold = '50%'; 
            this.initShareBar();
        }

        initShareBar() {
            if(this.contentTarget.length < 1) {
              this.element.addClass( this.showClass);
              return;
            }
            if(intersectionObserverSupported) {
              this.initObserver(); 
            } else {
              this.element.addClass(this.showClass);
            }
        }

        initObserver() {
            const self = this;
            var observer = new IntersectionObserver(
              function(entries, observer) { 
                self.element.classList.toggle( self.showClass, entries[0].isIntersecting);
              }, 
              {
               rootMargin: "0px 0px -"+this.threshold+" 0px"}
            );
            observer.observe(this.contentTarget[0]);
        }
    }

    const stickyShareBar = document.getElementsByClassName('js-sticky-sharebar'), …
Run Code Online (Sandbox Code Playgroud)

html javascript css intersection-observer

4
推荐指数
1
解决办法
835
查看次数