Bootstrap 4粘顶停止工作

时间:2018-06-23 21:50:32

标签: html twitter-bootstrap bootstrap-4

我正在使用Bootstrap卡上的sticky-top功能,因为用户滚动时会遵循它们。但是我发现了一种怪异的行为,其中一列中的卡片会变得“不粘”,因为用户会越过该列中的最后一张卡片。

在我为这个问题编写示例小提琴时,我发现它按预期工作了:

as you scroll here, a card in middle column keeps following

所以我直接从我的项目中举了一个例子,并进行了清理:

here the card in middle column stops following as soon as it goes past last card

我不认为这是一个错误,但是我不确定是什么破坏了sticky-top功能。如何防止这种情况发生?

2 个答案:

答案 0 :(得分:2)

好,我在这里呆了一段时间,因为我也对此感到好奇。

在您的代码中,您有<div class="tags">,这使您的粘性元素无法走得更远,因为它包裹了您的整个专栏,还有其他position

This是删除div.tags后的外观。

答案 1 :(得分:2)

默认情况下,Bootstrap列设置为其父元素高度的100%。通过将卡片包装在另一个div元素的第二列中,可以将“ .sticky-top”类所引用的父容器从Bootstrap列更改为“ .tags” div。如果要保留“ .tags” div,请在CSS文件中创建一个规则,使其与其父列的高度匹配:

.tags {
  height: 100%;
}

或者只是在打开的“ .tags” div中使用Bootstrap“ .h-100”类来完成相同的事情:

<div class="tags h-100">

编辑:如“ ajax333221”所示(jsfiddle.net/8pLfg5n1),前面的两个解决方案导致“ .tags” div溢出其父容器。发生这种情况是因为第二列中的顶部卡在“ .tags” div之外。因此,分配给“ .tags”的父列高度开始于第一张卡片的结尾而不是列的顶部。

由于许多Bootstrap 4功能已经需要jQuery库,因此可以在此处使用它来计算“ .tags” div并将其自定义高度,以适合父容器中的剩余空间:

$(document).ready(function(){
    var colHeight;
    //Get column height
    $('.tags').each(function(){ 
      colHeight = $(this).parent().height();
    });
    //Subtract height of cards preceding .tags div
    $('.topCard').each(function(){
      colHeight -= $(this).height();
    });
    /*Set .tags div height to remaining space in 
    column to prevent overflow*/
    $('.tags').each(function(){
      $(this).css('height', colHeight);
    });
 }); 

此脚本利用了我添加到“ .tags”上方同一列中可见卡中的“ .topCard”类,以区分它们。

<div class="card bg-primary w-100 topCard">

这是“ ajax333221”提供的演示的更新版本:https://jsfiddle.net/8pLfg5n1/33/

相关问题