将粘性块从一个地方移到另一个地方

时间:2015-06-17 17:22:14

标签: javascript jquery html css

我的页面上有粘性块。当视口底部到达顶部时,它会粘到页面底部。并且块必须在页脚之前停止粘性(当块的底部到达页脚顶部时)并保持在页脚之前。

问题在于在页脚之前插入块:当按钮到达页脚时没有任何反应。为什么会这样?

HTML

<header>
  <div class="block"></div>
</header>
<main></main>
<footer></footer>

CSS

header {
  position: relative;
}
.block {
  position: absolute;
  bottom: 10px;
}
.block-fixed {
  position: fixed;
  bottom: 0;
}

JS

$(function() {
  var blockPrimaryPosition = $(".block").offset().top; 

  function makeSticky() {
    var block = $(".block");
    var blockHeight = block.offset().top + 75; // coordinate of the bottom side of the block at any time
    var totalHeight = $(window).scrollTop() + $(window).height(); // coordinate of the bottom of the viewport relative to the document
    if (totalHeight >= blockPrimaryPosition) {
      block.addClass("block-fixed");
    } else if (buttonsHeight >= $("footer").offset().top) {
      $("footer").before(block);
      block.removeClass("block-fixed");
    } else {
      block.removeClass("block-fixed");
    };
  };

  $(window).scroll(function() {
    makeSticky();
  });
});

0 个答案:

没有答案