簡體   English   中英

滾動期間底部的粘性側邊欄

[英]Sticky sidebar from bottom during scrolling

我打算像側邊欄一樣重新創建 Medium.com。 這就是我現在所擁有的,但還遠未結束。

打開下面的 JSFiddle 更好地理解; 我希望執行以下操作:

  1. 當你向下滾動時,它突然粘在底部。 我如何讓它在滾動時逐漸粘住?
  2. 因為它使用position: fixed ,它在不尊重布局的情況下向右側移動。 我該如何解決?
  3. 當您向上滾動並且空間較少時,它會與標題重疊,如屏幕截圖所示。 同樣,很可能是因為使用了position: fixed

我該如何解決? 我知道有粘性工具包可以完成這項工作,但我不能使用任何插件。

HTML:

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      Header and Menu is placed here.
      <hr />
    </div>
    <div class="col-xs-8">
       <p>This is the main body which the user would be scrolling infinitely as more data gets loaded on scroll.</p>
    </div>
    <div class="col-xs-4">
      <div id="sidebar">
        <p>
          This is the sidebar which I want to stop when it reaches the bottom like the one shown in medium dot com
        </p>
      </div>
    </div>
  </div>
</div>

Javascript:

function scrollCheck() {
    var $right = $('#sidebar'),
        scrollTop = $(window).scrollTop(),
        windowHeight = $(window).height(),
        docHeight = $(document).height(),
        rightHeight = $right.height(),
        distanceToTop = rightHeight - windowHeight,
        distanceToBottom = scrollTop + windowHeight - docHeight;
    if (scrollTop > distanceToTop) {

        $right.css({
            'position': 'fixed',
            'bottom': (scrollTop + windowHeight > docHeight ? distanceToBottom  + 'px' : '0px')
        });
    }
    else {
        $right.css({
            'position': 'relative',
            'bottom': 'auto'
        });
    }
}

$(window).bind('scroll', scrollCheck);

JSFIDDLE

我會回答你的問題。 首先編輯過的 Fiddle

至於你的問題:

  1. 突然粘到底部是因為元素不是頁面的全長,所以把它粘在底部固定位置會導致它跳到那里。 而我所做的更改使其粘在頂部不會有這種跳轉,因為滾動時元素位於屏幕頂部,因此可以謹慎地固定在那里。
  2. 這是因為元素沒有固定的width和設置position: fixed; 意味着元素寬度不再由父元素設置,而是由視口設置。 因此它會擴展以填充視口中的所有寬度。
  3. 發生這種情況是因為position: fixed; 在元素原始位置上方滾動時從未被刪除,Js 中更新的 if 語句現在刪除了帶有position: fixed;的類position: fixed; 在其原始位置上方滾動時。

更詳細地了解我所做的更改。

我添加了一個 CSS 類,因此.toggleClass可用於使函數更.toggleClass

.docked-sidebar {
  position: fixed;
  top: 0;
}

我還更改了 if 語句的條件,以便它們起作用。 使用.offset().top; 獲取側邊欄和頁面頂部之間的距離,同時刪除大多數不需要的其他變量。 最后,我創建了 bool 變量( isDocked ),以便不會多次觸發相同的條件。

var $right = $('#sidebar'),
  isDocked = false,
  initOffsetTop = $right.offset().top;


function scrollCheck() {
  var scrollTop = $(window).scrollTop(),
    offsetTop = $right.offset().top;

  if (!isDocked && ((offsetTop - scrollTop) < 0)) {
    $right.toggleClass("docked-sidebar");
    isDocked = true;
  } else if (isDocked && scrollTop <= initOffsetTop) {
    $right.toggleClass("docked-sidebar");
    isDocked = false;
  }
}

為了像示例網站一樣堅持底部然后頂部,我建議檢查這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM