>我有一个 100% 高度的div,下面有一个导航,下面还有更多内容。
当用户滚动通过导航时,它会粘在页面顶部,当用户回到 100% 高度div 时,导航被抛在后面。
由于div 高度为 100%,因此导航的"数据偏移顶部"需要动态更改。
以下代码适用于此:
$('#navigation').affix({
offset: {
top: $('#hero').height()
}
});
但是,当我调整页面大小时,偏移量的值不会重新添加到偏移量中。
以下代码检查页面高度是否要更改,然后将新高度提供给数据偏移顶部,但它没有函数 affixChange() {
$('#navigation').attr('data-offset-top', $('#hero').height());
$('#navigation').affix({
offset: {
top: $('#hero').height()
}
});
}
affixChange();
setInterval(function(){
affixChange();
console.log($('#hero').height());
}, 1000)
- 为什么我的方法不起作用?
- 有没有更好的方法可以做到这一点?
Bootstrap 让你可以传递一个函数来动态计算偏移量:
$('#navigation').affix({
offset: {
top: function() { return $('#hero').height(); }
}
});
如果您需要动态设置data-offset-top
,则需要手动处理。虽然domachine
提供了正确的答案,但我想在这里提供一种方法来重新计算页面大小调整的值,并添加一个空格支架,以便粘贴流畅,例如,粘贴内容时不会跳页。这对我来说是一个问题。
- 它动态地重新计算
data-offset-top
- 它动态设置偏移空间。粘贴时空格将替换附加物
所以我使用以下 HTML:
<div class="my-affix" data-spy="affix" data-offset-top-dynamic="true" data-content-space-holder="#my-affix-space-holder"></div>
<div id="my-affix-space-holder"></div>
以下 CSS:
.my-affix + #my-affix-space-holder {
display: none;
}
.my-affix.affix + #my-affix-space-holder {
display: block;
}
还有一个JS脚本:
var $dynamicAffixes = $('[data-offset-top-dynamic]');
$dynamicAffixes.each(function(){
// data-target is used for the element that should be affixed while data-spy is used to have some scroll breakpoint
var $thisAffix = $(this);
var $thisAffixMarginPlaceholder = $($thisAffix.attr('data-content-space-holder'));
var currentAffixHeight = $thisAffix.outerHeight();
// Assign the affix height to content placeholder - to add a margin in the page because of missing content
$thisAffixMarginPlaceholder.css('height', currentAffixHeight);
// Initialize affix height where it should trigger to become sticky
$thisAffix.affix({
offset: {
top: Math.round($(this).offset().top)
}
});
$(window).on('resize', function(){
var isAlreadyAffixed = false;
// Restore affix to its original position if scrolled already so we can calculate properly
if ($thisAffix.hasClass('affix')) {
$thisAffix.removeClass('affix');
isAlreadyAffixed = true;
}
var currentAffixPosition = Math.round($thisAffix.offset().top);
var currentAffixHeight = $thisAffix.outerHeight();
$thisAffix.data('bs.affix').options.offset.top = currentAffixPosition; // a hack
$thisAffixMarginPlaceholder.css('height', currentAffixHeight);
if (isAlreadyAffixed) {
$thisAffix.addClass('affix');
$thisAffix.affix('checkPosition');
}
});
});
您是否尝试过监视窗口以调整大小事件?
$(window).resize(function() {
affixChange();
});