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

求助:如何通过window.scrollY控制squareOne与squareTwo的显示隐藏?

滚动触发元素显示/隐藏的解决方案

直接给你修复后的完整代码,核心是正确监听滚动事件并覆盖所有滚动场景:

HTML 结构

<div class="square squareOne">方块1</div>
<div class="square squareTwo">方块2</div>

CSS 样式

/* 通用方块样式,默认隐藏 */
.square {
  width: 100px;
  height: 100px;
  position: fixed;
  top: 20px;
  left: 20px;
  display: none;
}

.squareOne {
  background: #ff4444;
}

.squareTwo {
  background: #0099cc;
}

JavaScript 逻辑

// 获取目标元素
const squareOne = document.querySelector('.squareOne');
const squareTwo = document.querySelector('.squareTwo');

// 滚动处理函数
function updateSquareVisibility() {
  const scrollY = window.scrollY;
  
  if (scrollY >= 20 && scrollY < 30) {
    squareOne.style.display = 'block';
    squareTwo.style.display = 'none';
  } else if (scrollY >= 30) {
    squareOne.style.display = 'none';
    squareTwo.style.display = 'block';
  } else {
    // 滚动位置小于20时,两个方块都隐藏
    squareOne.style.display = 'none';
    squareTwo.style.display = 'none';
  }
}

// 绑定滚动事件
window.addEventListener('scroll', updateSquareVisibility);

// 页面加载时执行一次,确保初始状态正确
updateSquareVisibility();

关键注意事项

  • 确保DOM元素已加载完成再获取,如果你把JS写在<head>里,需要包裹在DOMContentLoaded事件中
  • 覆盖所有滚动区间的判断,避免出现某个区间没有对应的状态处理
  • 滚动事件会频繁触发,若后续需要优化性能,可以添加防抖处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:05:05