html
<div class="search-box">
<input type="text" placeholder="搜索框">
</div>
<div class="content">
<h1>这里是网页顶部</h1>
</div>
<h1>已到达网页底部</h1>
css
.search-box {
position: relative;
height: 50px;
background-color: #f9f9f9;
padding: 10px;
}
.search-box.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
}
.content {
height: 2000px; /* 假设页面内容超过2000px */
}
JavaScript
window.addEventListener('scroll', function() {
var searchBox = document.querySelector('.search-box');
var contentTop = document.querySelector('.content').offsetTop;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (scrollTop > contentTop) {
searchBox.classList.add('fixed');
} else {
searchBox.classList.remove('fixed');
}
});