我尝试在顶部修复:滚动后ID为“ sticky”的div,但不起作用,我认为javascript代码是问题所在。
有人可以帮我做吗。

function sticky_relocate() {
  var window_top = $(window).scrollTop();
  var div_top = $('#sticky-anchor').offset().top;
  if (window_top > div_top) {
    $('#sticky').addClass('stick');
    $('#sticky-anchor').height($('#sticky').outerHeight());
  } else {
    $('#sticky').removeClass('stick');
    $('#sticky-anchor').height(0);
  }
}

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

#sticky {
  background-color: red;
  height:140px;
  z-index: 1;
}

#sticky.stick {
  position: fixed;
  top: 0;
  z-index: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sticky-anchor"></div>
<div id="sticky">
  <ul class="menu">
    <li><a href="#">Nos Produits</a></li>
  </ul> <!--  ul end .menu -->
</div>

最佳答案

您需要包括jQuery



function sticky_relocate() {
  var window_top = $(window).scrollTop();
  var div_top = $('#sticky-anchor').offset().top;
  if (window_top > div_top) {
    $('#sticky').addClass('stick');
    $('#sticky-anchor').height($('#sticky').outerHeight());
  } else {
    $('#sticky').removeClass('stick');
    $('#sticky-anchor').height(0);
  }
}

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

body {
height: 2000px;
background: grey;
}

#sticky {
  background-color: red;
  height: 140px;
  z-index: 1;
}

#sticky.stick {
  position: fixed;
  top: 0;
/* added for demo */
  left: 0;
  right: 0;
  z-index: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sticky-anchor"></div>
<div id="sticky">
  <ul class="menu">
    <li><a href="#">Nos Produits</a></li>
  </ul>
  <!--  ul end .menu -->
</div>

10-04 21:29