把div固定在网页顶部

时间:2023-03-08 15:32:16

很多网站都有把某一块固定在顶部的功能,今天上网搜搜然后自己又写了一遍,贴出来给大家看看,哪天用到的时候自己也可以随时看看

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
//获取要定位元素距离浏览器顶部的距离
var navH = $(".hb").offset().top;
//滚动条事件
$(window).scroll(function() {
//获取滚动条的滑动距离
var scroH = $(this).scrollTop();
//滚动条的滑动距离大于等于定位元素距离浏览器顶部的距离,就固定,反之就不固定
if (scroH >= navH) {
$(".hb").css({ "position": "fixed", "top": });
}
else if (scroH < navH) {
$(".hb").css({ "position": "static" });
}
})
})
</script>
</head>
<body>
<div style=" height: 300px;">
空div</div>
<div class="hb" style="height: 100px; width: 100%; background: #999">
移动到顶部固定不变</div>
<div style="background: #ccc; height: 1500px;">
空div</div>
</body>
</html>

西游记告诉我们:凡是有后台的妖怪都被接走了,凡是没后台的都被一棒子打死了。

相关文章