Показать сообщение отдельно
  #8 (permalink)  
Старый 17.12.2016, 18:11
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,134

фиксация блока при скролле
<!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>
Ответить с цитированием