Bootstrap 4提供了两种方法来创建固定(fixed)和粘滞(sticky)标题:使用position: fixed;
和position: sticky;
CSS属性。
基础概念: 固定标题是指在页面滚动时,标题始终保持在视口的顶部,不会随着页面内容的滚动而移动。
优势:
类型:
应用场景:
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fixed Header Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.fixed-header {
position: fixed;
top: 0;
width: 100%;
z-index: 1000;
}
</style>
</head>
<body>
<header class="fixed-header bg-primary text-white p-3">
<h1>My Fixed Header</h1>
</header>
<div style="height: 2000px;">
<!-- 页面内容 -->
</div>
</body>
</html>
基础概念: 粘滞标题在滚动到特定位置时固定在视口顶部,当用户向上滚动回到该位置时,标题会恢复到原来的位置。
优势:
类型:
应用场景:
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sticky Header Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.sticky-header {
position: sticky;
top: 0;
z-index: 1000;
}
</style>
</head>
<body>
<header class="sticky-header bg-warning text-dark p-3">
<h1>My Sticky Header</h1>
</header>
<div style="height: 2000px;">
<!-- 页面内容 -->
</div>
</body>
</html>
问题:粘滞标题在某些浏览器中不起作用。
原因:
position: sticky;
需要正确的父元素设置。解决方法:
overflow: hidden;
或其他可能影响粘滞定位的CSS属性。window.addEventListener('scroll', function() {
var header = document.querySelector('.sticky-header');
if (window.pageYOffset > 100) {
header.style.position = 'fixed';
header.style.top = '0';
} else {
header.style.position = '';
header.style.top = '';
}
});
通过以上方法,可以有效地创建和管理固定和粘滞标题,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云