Pobiegłem w dziwny problem z układem i nie mogłem myśleć o sposobie, aby to zrozumieć. Tytuł może być trochę mylący, ale pozwól mi pokazać kod.

#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>

Załóżmy, że rzutnia nie jest wystarczająco wysoka i musimy przewijać całą drogę do dołu, aby zobaczyć fioletowy blok (bottom div).

Chcę:

  1. Kiedy przewijamy z góry do dołu, a blok fioletowy nie pojawił się jeszcze, przezroczysty blok jest lepki do 20px nad dnem pomarańczowego bloku. Który został wykonany z position: sticky.

  2. Gdy purpurowy blok zacznie się pojawiać, zatrzymaj przezroczysty blok przed przesuwaniem się i trzymaj go w pozycji, w której znajduje się 20px powyżej dolnej części pomarańczowego bloku, jak to jest przycisk pływający. To nie powiedzie się, ponieważ lepki element jest Ustawiony zgodnie z normalnym przepływem dokumentu. Więc w tym przypadku, gdy purpurowy blok całkowicie pojawia się, przezroczysty blok znajduje się 20px poniżej dolnej części pomarańczowego bloku.

Zastanawiam się, czy są jakieś sposoby realizacji obu. Byłoby dobrze, gdybyśmy zrealizować to tylko CSS. Ale preferowany jest również prosty kod JS. Dzięki!

4
Shi Cheng 28 luty 2019, 05:07

2 odpowiedzi

Najlepsza odpowiedź

Jednym z pomysłu jest przesuwanie lepkiego elementu na górną część kontenera zamiast dołu i polegać na negatywnym marginesie, aby uniknąć normalnego zachowania przepływu, gdy jest na górze, to zatrzyma się, gdy sięgną do dolnej krawędzi kontenera.

Sprawdź poniżej komentarz, aby lepiej zrozumieć. Jedyną wadą jest to, że niektóre wartości muszą być ustawione ręcznie na podstawie wysokości elementu. Zanotuj również wartość górnej, która również musi być ustawiona ręcznie w zależności od rozmiaru ekranu, aby symulować dolne zachowanie kija.

#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>
3
Temani Afif 28 luty 2019, 09:05

Dlaczego to nie działa z CSS

Jeśli chcesz uniknąć negatywnych marginesów lub radzenia sobie ze zmiennymi wysokościami, to nie działa z CSS. Twój względny pojemnik #sticky-container ma zawartość #full-height-content za pomocą 400px wysokość. Pozycja {x3}} nie może działać w obu sposobach. Możesz znaleźć to do jego przewijania przodków (dokument) lub ustawienie właściwości przelewowej na #sticky-container Możesz go tam ustawić.

Element jest umieszczony zgodnie z normalnym przepływem dokumentu, a następnie przesunięcie względem najbliższego przewijanego przodka i blokującego bloku (najbliższy przodek poziomu bloku)

Jeśli ustawisz nieruchomość przelewową (powiedzmy overflow-y: hidden) na #sticky-container, a następnie element #sticky-content potencjalnie wynosi 400px w dokumencie, a nie 20px z dna rzutni (co chcesz).

Wydaje się, że chcesz, aby lepki element trzymał się rzutni, a następnie w sposób "Stick" Absolutnie do elementu #sticky-container, gdy #bottom staje się widoczne.

Jak javascript może to rozwiązać

Używając JavaScript i IntersectionObserver mieć to w obie strony. #sticky-content będzie zachowywać się tak, jak go masz, aż #bottom wchodzi do rzutni. Po tym, że dodajemy klasę (.is-absolute) do #sticky-content, która pozycjonuje go absolute, a nie sticky, a następnie będzie 20px z dna Jego względny rodzic #sticky-container (i już nie ma już przewijania przodków, rzutni). Intersectionobserver obsługuje odwrotność usuwania tej klasy, gdy #bottom pozostawia rzutnię.

Weź Uwaga: IntersectionObserver jest dość nowa i Nie jest jeszcze szeroko wspierany główne przeglądarki. Możesz mieć szczęście z 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
jaasum 28 luty 2019, 17:18