!DOCTYPE html html langzh-CN head meta charsetUTF-8 / title滚动吸顶淡入淡出/title style * { margin: 0; padding: 0; box-sizing: border-box; } /* 吸顶元素 */ .sticky-header { position: fixed; top: 0; left: 0; width: 100%; height: 60px; line-height: 60px; text-align: center; background: #fff; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); font-size: 18px; z-index: 999; /* 默认隐藏 过渡动画 */ opacity: 0; visibility: hidden; transition: opacity 0.3s ease, visibility 0.3s ease; } /* 显示状态 */ .sticky-header.show { opacity: 1; visibility: visible; } /* 页面长内容 */ .content { height: 150px; line-height: 150px; text-align: center; background: #f5f5f5; margin: 10px 0; } /style /head body !-- 滚动后固定在顶部的元素 -- div classsticky-header idstickyBox 我是固定在顶部的内容 /div !-- 页面内容 -- div classwrap div classcontent内容 1/div div classcontent内容 2/div div classcontent内容 3/div div classcontent内容 4/div div classcontent内容 5/div div classcontent内容 6/div div classcontent内容 7/div div classcontent内容 8/div div classcontent内容 9/div div classcontent内容 10/div /div script const stickyBox document.getElementById(stickyBox); // 滚动超过 100px 触发吸顶 const triggerDistance 100; window.addEventListener(scroll, function () { const scrollTop window.scrollY || document.documentElement.scrollTop; if (scrollTop triggerDistance) { stickyBox.classList.add(show); } else { stickyBox.classList.remove(show); } }); /script /body /html