@moiseev1788

Как остановить фиксированный блок перед футером?

Есть страница, где присутствует фиксированный блок, как указать данному блоку чтобы он остановился, как только он прикоснется футера? Сейчас он на него залезает, а должен остановится.

Код ниже:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<header>Шапка</header>
<div class="container">
  <div class="row">
    <div class="col-8">
      <div class="article__article">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus recusandae, quae tenetur hic tempora ullam consectetur porro odit? Quidem autem sint in, debitis eligendi inventore qui quas explicabo doloremque quis.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus recusandae, quae tenetur hic tempora ullam consectetur porro odit? Quidem autem sint in, debitis eligendi inventore qui quas explicabo doloremque quis.</p>
      </div>
      <div id="get_article"></div>
    </div>
    <div class="col-4">
      <div id="aside-fixed">
        <div class="aside-fixed__red">
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non, autem similique ullam dolor corporis mollitia harum, dicta odio nobis accusamus facilis excepturi voluptate eum sunt cupiditate labore tempore. Voluptas, at!</p>
        </div>
      </div>
    </div>
  </div>
</div>
<footer>футер</footer>


'use strict';

var width = $(window).width();
var height = $(window).height();
var $article_list = $('#article_list');
var $article_aside = $('#aside-fixed');
var sticky = 0;
var send = true;
var page = {
  init: function init() {
    var top = page.getScrollTop();

  },

  getScrollTop: function() {
    if (typeof pageYOffset != 'undefined') {
      //most browsers except IE before #9
      return pageYOffset;
    } else {
      var B = document.body; //IE 'quirks'
      var D = document.documentElement; //IE with doctype
      D = D.clientHeight ? D : B;
      return D.scrollTop;
    }
  },
  scrollPage: function() {
    var topPos = $('#get_article').offset().top;
    var top = page.getScrollTop();
    var diff = topPos - top;
    // console.log( diff +'||'+ top +'||'+ topPos);

    if ((diff <= (height - sticky)) && send) {

      var $last_article = $article_list.children().last()
      var _url = $last_article.attr('data-url');
      var _url_aside = $last_article.attr('data-aurl');
      send = false;
      if (_url) {
        $.ajax({
          url: _url,
          type: 'GET',
          dataType: 'html',
          beforeSend: function() {
            // включение прелоудера
            send = false;
          },
          complete: function() {
            // отключение прелоудера
          },
          success: function(obj) {
            send = true;
            $article_list.append(obj);

            const players = Array.from(document.querySelectorAll('#videoPlay')).map(p => new Plyr(p));
            const plyrs = Array.from(document.querySelectorAll('#plyrVideo')).map(plyrs => new Plyr(plyrs));
            //добвляем обновление правого блока
            page.getAsideHtml(_url_aside);

          },
          error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + xhr);
          }
        });
      }
    };

    if ($('.aside-fixed__red').length > 0) {

      if ($(window).width() > 991) {
        var sc_topPos = $('.aside-fixed__red').offset().top;
        var sc_top = page.getScrollTop();
        var sc_diff = sc_topPos - sc_top;
        console.log(sc_diff + '||' + sc_top + '||' + sc_topPos);
        if ((sc_diff <= 240) && (sc_top >= 240)) {
          $('.aside-fixed__red').addClass('aside-fixed__blue');
        } else {
          $('.aside-fixed__red').removeClass('aside-fixed__blue');
        }
      }

    };
  },
  getAsideHtml: function(_url_aside) {
    send = true;
    if (_url_aside) {
      $.ajax({
        url: _url_aside,
        type: 'GET',
        dataType: 'html',
        beforeSend: function() {
          // включение прелоудера
          send = false;
        },
        complete: function() {
          // отключение прелоудера
        },
        success: function(obj) {
          send = true;
          //добвляем обновление правого блока
          $('.aside-fixed__red').html(obj)
        },
        error: function(xhr, ajaxOptions, thrownError) {
          console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + xhr);
        }
      });
    }
  }
};
/**
 * section init
 */
$(document).ready(function() {
  page.init();
});
/**
 * section scroll animation
 */
$(document).on("scroll", function() {
  page.scrollPage();

});

$(window).resize(function() {
  page.resize();
});


header {
  background: blue;
  height: 50px;
  text-align: center;
  color: white;
  margin-bottom: 30px;
}

footer {
  background: red;
  height: 100px;
  text-align: center;
  color: white;
}

.article__article {
  height: 1200px;
}

#aside-fixed {
  width: 150px;
  position: relative;
  height: 100%;
  @media screen and (max-width: 1024px) {
    display: none;
    height: 0;
  }
}

.aside-fixed__red {
  position: relative;
  width: 450px;
  height: 600px;
  transition: all .3s;
  background: green;
}

.aside-fixed__blue {
  position: fixed !important;
  width: 450px;
  top: 200px;
}


Ссылка на CodePen
  • Вопрос задан
  • 429 просмотров
Пригласить эксперта
Ответы на вопрос 1
Raxen
@Raxen
TechLead Frontend Developer, Beeline
Используйте position: sticky с top: 0 и bottom: 0; js тут не нужен. Для старых браузеров можно поискать полифил в интернетах. Форк вашего кода с решением со стики https://codepen.io/irodger/pen/eYJwxKx

Кстати, если вы не используете какой-нибудь из css препроцессоров, то эти строчки так не работают
#aside-fixed {
  width: 150px;
  position: relative;
  height: 100%;
  @media screen and (max-width: 1024px) {
    display: none;
    height: 0;
  }
}

В ванильном CSS надо так
#aside-fixed {
  width: 150px;
  position: relative;
  height: 100%;
}

@media screen and (max-width: 1024px) {
  #aside-fixed {
    display: none;
    height: 0;
  }
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы