<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js导航栏置顶</title>
<style>
* {
margin: 0;
padding: 0;
}
.nav_top {
height: 50px;
background-color: red;
}
.nav_bottom {
height: 100px;
background-color: yellow;
transition: all 0.6s;
}
</style>
</head>
<body>
<!-- 导航栏 -->
<nav>
<header class="nav_top"></header>
<header class="nav_bottom" id="top"></header>
</nav>
<section style="height: 1000px;"></section>
<!-- 监听滚动导航栏置顶 -->
<!-- 引用jquery -->
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// 获取id是top元素的top坐标。
var top = $("#top").offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() >= 50) {
$("#top").attr("style", "position:fixed;top:0;z-index:999;width:100%;height:50px;");
} else {
$("#top").attr("style", "");
}
}).trigger("scroll");
</script>
</body>
</html>