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

如何用JavaScript检测图片重叠并自动控制上层固定图片显隐

JavaScript 实现固定元素重叠自动显隐方案

核心实现逻辑

  • 用getBoundingClientRect()接口获取两个元素在视口中的位置坐标
  • 对比两个元素的上下左右边界,判断是否发生重叠
  • 监听页面滚动事件,滚动时实时检测重叠状态,控制固定元素显隐
  • 可选添加节流函数优化滚动事件触发频率,降低性能损耗

完整代码实现

首先你需要替换代码中的#fixedFloat(右侧固定元素ID)、#contentImg(正文需要避让的图片ID)为你实际的元素ID:

// 重叠检测工具函数
function isElementOverlap(el1, el2) {
  const rect1 = el1.getBoundingClientRect();
  const rect2 = el2.getBoundingClientRect();
  // 边界不重叠的四种情况,取反就是重叠
  return !(
    rect1.right < rect2.left || 
    rect1.left > rect2.right || 
    rect1.bottom < rect2.top || 
    rect1.top > rect2.bottom
  );
}

// 节流函数,避免滚动事件触发过于频繁
function throttle(fn, delay = 100) {
  let timer = null;
  return function(...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args);
        timer = null;
      }, delay);
    }
  }
}

// 显隐控制逻辑
const fixedEl = document.querySelector('#fixedFloat');
const contentImgs = document.querySelectorAll('#contentImg'); // 如果有多个正文图片直接选所有即可

function controlFloatVisibility() {
  let hasOverlap = false;
  // 遍历所有正文图片,只要有一个重叠就标记为需要隐藏
  contentImgs.forEach(img => {
    if (isElementOverlap(fixedEl, img)) {
      hasOverlap = true;
    }
  });
  // 控制显隐,用opacity配合CSS过渡效果更自然,也可以用display: none/block
  fixedEl.style.opacity = hasOverlap ? '0' : '1';
  // fixedEl.style.display = hasOverlap ? 'none' : 'block';
}

// 初始化执行一次,避免页面加载时就重叠却没触发
controlFloatVisibility();
// 绑定滚动监听,加节流优化
window.addEventListener('scroll', throttle(controlFloatVisibility));

配套CSS优化

你可以给现有的.sec类添加过渡属性,让显隐动画更丝滑:

.sec {
  /* 原有属性保留,新增以下代码 */
  transition: opacity 0.2s ease;
  /* 避免透明时还遮挡点击 */
  pointer-events: none;
}

注意事项

  • 如果正文有多个需要避让的图片,修改选择器选中所有对应图片即可,代码里的遍历逻辑已经兼容多图片场景
  • 如果固定元素的显隐不需要动画,直接切换display属性即可,不需要加过渡样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:18:03