Как сделать липкий элемент «плавать» - PullRequest
0 голосов
/ 28 февраля 2019

Я столкнулся со странной проблемой макета и не мог придумать, как это выяснить.Название может быть немного запутанным, но позвольте мне показать код.

#root-container {
  display: flex;
}

#container1 {
  width: 100px;
  height: 500px;
  background-color: grey;
}

#sticky-container {
  width: 320px;
  max-height: 500px;
  position: relative;
  background-color: lightgrey;
}

#sticky-container-header {
  width: 320px;
  height: 100px;
  background-color: #2f4d92;
}

#full-height-content {
  width: 100%;
  height: 400px;
  overflow-y: scroll;
  background-color: #d67e23;
}

#sticky-content {
  width: 80%;
  height: 100px;
  position: sticky;
  bottom: 20px;
  background-color: rgba(0,0,0,0.5);
}

#bottom {
  width: 420px;
  height: 100px;
  background-color: purple;
}
<div id='root-container'>
  <div id="container1"></div>
  <div id="sticky-container">
    <div id='sticky-container-header'></div>
    <div id='full-height-content'>
      Saw yet kindness too replying whatever marianne. Old sentiments resolution admiration unaffected its mrs literature. Behaviour new set existence dashwoods. It satisfied to mr commanded consisted disposing engrossed. Tall snug do of till on easy. Form not calm new fail. 

His followed carriage proposal entrance directly had elegance. Greater for cottage gay parties natural. Remaining he furniture on he discourse suspected perpetual. Power dried her taken place day ought the. Four and our ham west miss. Education shameless who middleton agreement how. We in found world chief is at means weeks smile. 

Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects. 

Must you with him from him her were more. In eldest be it result should remark vanity square. Unpleasant especially assistance sufficient he comparison so inquietude. Branch one shy edward stairs turned has law wonder horses. Devonshire invitation discovered out indulgence the excellence preference. Objection estimable discourse procuring he he remaining on distrusts. Simplicity affronting inquietude for now sympathize age. She meant new their sex could defer child. An lose at quit to life do dull. 

Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung. 
Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he. 

Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name. 

Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had. 

Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated especially. Unfeeling one provision are smallness resembled repulsive. 

Entire any had depend and figure winter. Change stairs and men likely wisdom new
    </div>
    <div id='sticky-content'></div>
  </div>
</div>
<div id="bottom">
</div>

Предположим, что область просмотра недостаточно высока, и нам нужно прокрутить весь путь вниз, чтобы увидеть фиолетовый блок (элемент bottom).

То, что я хочу, это:

  1. , когда мы прокручиваем сверху вниз, и фиолетовый блок еще не появился, прозрачный блок липкий на 20 пикселей вышенижняя часть оранжевого блока.Что было сделано с position: sticky.

  2. , когда фиолетовый блок начинает появляться, не позволяйте прозрачному блоку двигаться вниз и удерживайте его в положении, где он находится на 20 пикселей выше нижней частиоранжевый блок, как будто это плавающая кнопка.Это терпит неудачу, так как липкий элемент расположен в соответствии с обычным потоком документа .Таким образом, в этом случае, когда фиолетовый блок полностью обнаруживается, прозрачный блок находится на 20 пикселей ниже нижней части оранжевого блока.

Интересно, есть ли какие-либо способы для реализации обоих.Было бы хорошо, если бы мы могли реализовать это только с помощью CSS.Но простой код JS также предпочтителен.Спасибо!

Ответы [ 2 ]

0 голосов
/ 28 февраля 2019

Почему это не будет работать с CSS

Если вы хотите избежать отрицательных полей или иметь дело с переменной высотой, то это не будет работать с CSS.Ваш относительный контейнер #sticky-container имеет содержимое #full-height-content с высотой 400px.Позиция sticky не может работать в обоих направлениях.Вы можете либо поместить его в его предшественника прокрутки (документ), либо установив свойство переполнения на #sticky-container, вы можете расположить его там.

Элемент позиционируется в соответствии с обычным потоком документа, а затем смещается относительно ближайшего предка прокрутки и содержащего блока (ближайшего предка уровня блока)

Если вы установите свойство переполнения (скажем, overflow-y: hidden) на #sticky-container, то ваш элемент #sticky-content потенциально будет на 400px вниз в документе, а не на 20px от нижней части области просмотра (что вам нужно).

Вы, похоже, хотите, чтобы липкий элемент прилипал к области просмотра, а затем каким-то образом "прилипал" к элементу #sticky-container, когда #bottom становился видимым.

Как может решить JavaScriptthis

Используя JavaScript и IntersectionObserver, вы можете получить его обоими способами.#sticky-content будет вести себя так, как у вас, пока #bottom не войдет в область просмотра.Как только это произойдет, мы добавим класс (.is-absolute) к #sticky-content, который позиционирует его absolute, а не sticky, и тогда он будет 20px от основания его относительного родителя #sticky-container (и больше не будетего прокручивающему предку, окну просмотра).IntersectionObserver будет обрабатывать обратное удаление этого класса, когда #bottom покидает область просмотра.

Обратите внимание: IntersectionObserver является довольно новым и пока широко не поддерживается всеми основными браузерами.Вам может повезти с polyfill .

// The elements we want to control
var stickyContent = document.querySelector('#sticky-content');
var stickyContentActiveClass = 'is-absolute';
var bottom = document.querySelector('#bottom');

// The function to call when #bottom intersects with the viewport
var callback = function(entries, observer) { 
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      stickyContent.classList.add(stickyContentActiveClass);
    } else {
      stickyContent.classList.remove(stickyContentActiveClass);
    }
  });
};

// Setting up the observer with an argument of 0 for the threshold
// Our callback function will run as soon as #bottom enters the viewport
var observer = new IntersectionObserver(callback, {threshold: 0});

// Tell our observer to watch #bottom
observer.observe(bottom);
#root-container {
  display: flex;
}

#container1 {
  width: 100px;
  height: 500px;
  background-color: grey;
}

#sticky-container {
  width: 320px;
  max-height: 500px;
  position: relative;
  background-color: lightgrey;
}

#sticky-container-header {
  width: 320px;
  height: 100px;
  background-color: #2f4d92;
}

#full-height-content {
  width: 100%;
  height: 400px;
  overflow-y: scroll;
  background-color: #d67e23;
}

#sticky-content {
  width: 80%;
  height: 100px;
  position: sticky;
  bottom: 20px;
  background-color: rgba(0,0,0,0.5);
}

#sticky-content.is-absolute {
  position: absolute;
}

#bottom {
  width: 420px;
  height: 100px;
  background-color: purple;
}
<div id='root-container'>
  <div id="container1"></div>
  <div id="sticky-container">
    <div id='sticky-container-header'></div>
    <div id='full-height-content'>
      Saw yet kindness too replying whatever marianne. Old sentiments resolution admiration unaffected its mrs literature. Behaviour new set existence dashwoods. It satisfied to mr commanded consisted disposing engrossed. Tall snug do of till on easy. Form not calm new fail. 

His followed carriage proposal entrance directly had elegance. Greater for cottage gay parties natural. Remaining he furniture on he discourse suspected perpetual. Power dried her taken place day ought the. Four and our ham west miss. Education shameless who middleton agreement how. We in found world chief is at means weeks smile. 

Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects. 

Must you with him from him her were more. In eldest be it result should remark vanity square. Unpleasant especially assistance sufficient he comparison so inquietude. Branch one shy edward stairs turned has law wonder horses. Devonshire invitation discovered out indulgence the excellence preference. Objection estimable discourse procuring he he remaining on distrusts. Simplicity affronting inquietude for now sympathize age. She meant new their sex could defer child. An lose at quit to life do dull. 

Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung. 
Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he. 

Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name. 

Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had. 

Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated especially. Unfeeling one provision are smallness resembled repulsive. 

Entire any had depend and figure winter. Change stairs and men likely wisdom new
    </div>
    <div id='sticky-content'></div>
  </div>
</div>
<div id="bottom">
</div>
0 голосов
/ 28 февраля 2019

Одна идея состоит в том, чтобы переместить липкий элемент в верхнюю часть контейнера вместо нижнего и полагаться на отрицательное поле, чтобы избежать нормального поведения потока, когда он находится сверху, тогда он остановится при достижении нижнего края контейнера.

Проверьте комментарий ниже, чтобы лучше понять.Единственным недостатком является то, что некоторые значения должны быть установлены вручную в зависимости от высоты элемента.Вы также заметите значение вершины, которое также необходимо установить вручную в зависимости от размера экрана, чтобы имитировать поведение нижней ручки.

#root-container {
  display: flex;
}

#container1 {
  width: 100px;
  height: 500px;
  background-color: grey;
}

#sticky-container {
  width: 320px;
  max-height: 500px;
  position: relative;
  background-color: lightgrey;
}

#sticky-container-header {
  width: 320px;
  height: 100px;
  background-color: #2f4d92;
}

#full-height-content {
  width: 100%;
  height: 400px;
  overflow-y: scroll;
  background-color: #d67e23;
  margin-top:-20px; /*same as the margin-bottom*/
}

#sticky-content {
  width: 80%;
  height: 100px;
  margin-top:-100px; /*same as height*/
  margin-bottom:20px; /*to avoid going under the bottom:20px we want*/
  position: sticky;
  top:calc(100vh - 100px - 20px);
  background-color: rgba(0,0,0,0.5);
}

#bottom {
  width: 420px;
  height: 100px;
  background-color: purple;
}

body {
  margin:0;
}
<div id='root-container'>
  <div id="container1"></div>
  <div id="sticky-container">
    <div id='sticky-container-header'></div>
    <div id='sticky-content'></div>
    <div id='full-height-content'>
      Saw yet kindness too replying whatever marianne. Old sentiments resolution admiration unaffected its mrs literature. Behaviour new set existence dashwoods. It satisfied to mr commanded consisted disposing engrossed. Tall snug do of till on easy. Form not calm new fail. 

His followed carriage proposal entrance directly had elegance. Greater for cottage gay parties natural. Remaining he furniture on he discourse suspected perpetual. Power dried her taken place day ought the. Four and our ham west miss. Education shameless who middleton agreement how. We in found world chief is at means weeks smile. 

Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects. 

Must you with him from him her were more. In eldest be it result should remark vanity square. Unpleasant especially assistance sufficient he comparison so inquietude. Branch one shy edward stairs turned has law wonder horses. Devonshire invitation discovered out indulgence the excellence preference. Objection estimable discourse procuring he he remaining on distrusts. Simplicity affronting inquietude for now sympathize age. She meant new their sex could defer child. An lose at quit to life do dull. 

Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung. 
Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he. 

Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name. 

Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had. 

Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated especially. Unfeeling one provision are smallness resembled repulsive. 

Entire any had depend and figure winter. Change stairs and men likely wisdom new
    </div>
  </div>
</div>
<div id="bottom">
</div>
...