关于页面向下滚动到元素位置,元素停靠顶部不动,当页面向上滚动到元素位置时,元素回到原来位置的效果,思路很简单,就是监听window滚动,获取元素到页面顶部位置,如果页面滚动距离大于元素到顶部距离,那么添加position:fixed;left:0;样式,小于则移出样式效果。
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
<style type="text/css">
*{ padding:0px; margin:0px;list-style:none;}
.box{width:300px;height:300px;background:red;margin:600px 200px;}
body{height:9999px;}
.fixed{position:fixed;top:0;margin-top:0;}
</style>
</head>
<body>
<div class="box">
fix的box模型
</div>
</body>
<script type="text/javascript" src="Util/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var box = $(".box");
var boxTop = box.offset().top; //元素到页面顶部的距离
$(document).scroll(function(){
var winScrollTop = $(window).scrollTop(); //获取窗口滚动的距离
console.log(winScrollTop);
if(winScrollTop > boxTop){
box.addClass("fixed");
}else{
box.removeClass("fixed");
}
});
});
</script>
</html>