调整大小时动态添加 Bootstrap 词缀 [英] Bootstrap affix dynamically on resize

查看:19
本文介绍了调整大小时动态添加 Bootstrap 词缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 100% 高度的 div,它下面有一个导航,下面有更多内容.

I have a 100% height div with a nav underneath it and more content under that.

当用户滚动通过导航时,它会粘在页面的顶部,当用户返回到 100% 高度时,导航会被留在后面.

When the user scrolls passed the nav it sticks to the top of the page and when the user goes back to the 100% height div the nav is left behind.

由于 div 的高度为 100%,因此导航的数据偏移顶部"需要动态更改.

As the div is 100% height the 'data-offset-top' for the nav needs to change dynamically.

以下代码适用于:

    $('#navigation').affix({
        offset: {
            top: $('#hero').height()
        }
    });

但是,当我调整页面大小时,偏移量的值不会被读取到偏移量中.

However when I resize the page the value of the offset does not get readded to the offset.

以下代码检查要更改的页面高度,然后将新高度提供给 data-offset-top 但它没有 ` 函数 afixChange(){

The following code checks for the page height to change and then gives the new height to the data-offset-top but it does not ` function affixChange() {

     $('#navigation').attr('data-offset-top', $('#hero').height());
    $('#navigation').affix({
        offset: {
            top: $('#hero').height()
        }
    }); 
 }

affixChange();
setInterval(function(){
 affixChange();
console.log($('#hero').height());
}, 1000)

  1. 为什么我的方法不起作用?
  2. 有没有更好的方法来做到这一点?

推荐答案

Bootstrap 让你可以传递一个函数来动态计算偏移量:

Bootstrap gives you the possibility to pass a function to calculate the offset dynamically:

$('#navigation').affix({
  offset: {
    top: function() { return $('#hero').height(); }
  }
});

这篇关于调整大小时动态添加 Bootstrap 词缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆