JavaScript学习笔记-元素在滚动条滑动一定高度后自动置顶

 <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<style type="text/css">
* { margin: 0; padding: 0; border: 0; }
.top { width: 100%; height: 30px; margin: 0 auto; text-align: center; background-color: #808080; color: #ffffff; margin-bottom: 20px; } .cen, .search, .search li { width: 1200px; height: 40px; margin: 0 auto; }
.cen { width: 100%; height: 50px; background-color: #ffffff; z-index: 10; }
.cen .search { background-color: #ff6a00; border-radius: 20px; }
.cen .search input { width: 1100px; height: 25px; margin-left: 50px; margin-top: 10px; background: none; outline: none; font-size: 14px; color: #000000; }
input::-webkit-input-placeholder { color: #808080; }
input:-moz-placeholder { color: #808080; } .con { width: 1200px; height: 1500px; margin: 0 auto; text-align: center; background-color: #ffd800; }
</style>
<script src="js/jquery-1.10.2.js"></script>
</head> <body>
<div class="top">顶部内容</div> <div class="cen"><!--这里注意一定要用一个宽100%的外框框起来,否则会影响美观,整体元素也会在固定置顶时靠左浮动-->
<div class="search"><!--这里在用一个宽为1200的元素将内容居中到页面-->
<input type="text" placeholder="请输入您需要查找的内容..." />
</div>
</div> <div class="con">页面内容</div> <script type="text/javascript">
//search在滚动条下滑一定高度后固定置顶
var titleH = $(".cen").offset().top; //获取滚动条下滑高度(即search固定置顶的条件)
$(window).scroll(function () { //window滚动条事件
var scroH = $(this).scrollTop(); //获取滚动条滑动的距离
if (scroH > titleH) { //判断滚动条滑动高度是否大于指定条件高度
$(".cen").css({ "position": "fixed", "top": 0 }); //大于就执行search固定置顶
} else if (scroH <= titleH) { //小于等于指定条件高度
$(".cen").css({ "position": "static" }); //则就恢复原位
}
});
</script> </body>
</html>
上一篇:jQuery实现表格行上移下移和置顶


下一篇:chainsql异常记录