滚动条滚动时头部导航栏固定在页面顶部的几种简单方法 |
您所在的位置:网站首页 › 网页的头部怎么做 › 滚动条滚动时头部导航栏固定在页面顶部的几种简单方法 |
一、使用css直接用固定定位position: fixed。
适合使用在导航栏有固定高度,避免导航栏下面的内容被遮盖。下面的盒子就需要调整top的距离。 示例代码: *{ margin: 0; padding: 0; } p{ height: 500px; } section{ padding-top: 40px; } div{ height: 40px; width: 100%; color: white; background-color: crimson; position: fixed; top: 0; } head11111111111111111111 2222222222222222 333333333333 444444444444444 555555555555555 666666666666666 777777777777777 88888888888888 效果:
适合不确定导航栏高度,不能调整导航栏下面盒子的top高度。 示例代码: div{ font-size: 50px; width: 100%; color: white; background-color: crimson; } let Head = document.getElementById('Head') window.onscroll = ()=>{ // 获取滚动距离 let top = document.documentElement.scrollTop || document.body.scrollTop; if (top != 0) { Head.style = "position: fixed;top: 0;" }else{ Head.style = "position: static;" } }效果: 三、使用position: sticky; 这个超简单,不用js,不用确定导航栏高度纯css,除了有些浏览器需要兼容。是css3新添加的属性。 示例代码: div{ font-size: 40px; width: 100%; color: white; background-color: crimson; position: sticky;/* 新属性sticky */ top: 0;/* 距离页面顶部距离 */ }效果:
|
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |