<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<style type="text/css">
.field{
position: relative;
border: 1px solid #000;
width: 800px;
height: 1800px;
}
.block{
margin: 10%;
width: 50px;
height: 50px;
background-color: red;
}
.block.fix {
background-color: #006400;
position: fixed;
margin-top: -7px;
}
</style>
<body>
<div class="field">
<div class="block"></div>
</div>
</body>
<script type="text/javascript">
window.onload = function() {
var b = true, d = $(".block"),h = d.offset().top, l = d.css("margin-left");
$(window).scroll(function() {
var a = h < $(window).scrollTop();
a != b && ((b = a) ? d.addClass('fix').css({"margin-left": l}) : d.removeClass('fix').css({"margin-left":""}))
})
};
</script>
</html>