Как сделать липкий элемент «плавать»

Ну, я должен сначала ответить на первую часть: что такое memoization?

Это всего лишь метод для торговли памятью за время. Подумайте о таблице умножения .

Использование изменяемого объекта в качестве значения по умолчанию в Python обычно считается плохим. Но если использовать его с умом, на самом деле может быть полезно реализовать memoization.

Вот пример, адаптированный из http://docs.python.org/2/faq/design.html # why-are-default-values-shared-between-objects

Используя mutable dict в определении функции, промежуточные вычисленные результаты могут быть кэшированы (например, при расчете factorial(10) после вычисления factorial(9) мы можем повторно использовать все промежуточные результаты)

def factorial(n, _cache={1:1}):    
    try:            
        return _cache[n]           
    except IndexError:
        _cache[n] = factorial(n-1)*n
        return _cache[n]

3
задан Temani Afif 28 February 2019 в 09:05
поделиться

1 ответ

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

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

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

0
ответ дан Temani Afif 28 February 2019 в 09:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: