You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测水平动画元素到达视口中心?跨浏览器兼容问题求助

问题:行内滚动图片的视口中心检测与样式切换兼容性问题

我需要实现一行通过transform动画的图片效果:当图片滚动到视口中心时,移除灰度滤镜(filter: grayscale(0%)),不在中心时保持黑白(filter: grayscale(100%)),效果如下:

行内图片中位于屏幕中间的图片为彩色,其余为黑白

我用IntersectionObserver写的方案在Firefox里正常,但Chrome只有鼠标移动时才生效,Safari完全没效果。调整options参数后,除了Firefox,其他浏览器表现还是不稳定。

实现代码如下:

const options = {
  root: document.body,
  rootMargin: '0% -50% 0% -50%',
  threshold: 0,
}

const observer = new IntersectionObserver((entries) => { 
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.style.filter = 'grayscale(0%)'
    } else {
      entry.target.style.filter = 'grayscale(100%)'
    }
  })
}, options)

const items = document.querySelectorAll('.img-container img');
items.forEach(img => observer.observe(img))

内容的提问来源于stack exchange,提问作者dras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 14:12:36