简体   繁体   English

如何使元素在特定点后停止滚动?

[英]How to make an element stop scrolling after a certain point?

Ok so as the question says, I have an element set on a point, but, for reasons, I need it to scroll a bit up but then stop on another fixed point. 好的,正如问题所述,我在一个点上设置了一个元素,但是出于某种原因,我需要将其向上滚动一点,然后在另一个固定点上停止。 My friend helped me with the code a bit but neither of us are really pro at Javascript so similar questions haven't really helped me figure this thing out. 我的朋友对我的代码有所帮助,但是我们俩都不是Java专家,所以类似的问题并没有真正帮助我弄清楚这件事。 My code for now is 我现在的代码是

function absToFix() {
  var udaljenost = $(window).scrollTop();
  var sideb = $('#sidebar').offset().top;
  var distance = (sideb - udaljenost);
  return distance;
}
$(document).ready(function() {
  var distance = absToFix();
  $(window).scroll(function() {
    distance = absToFix();
    if (distance < 220) {
      $('#sidebar').css({
        position: 'fixed',
        top: '220px'
      });
    } else {
      $('#sidebar').css({
        position: 'absolute',
        top: '340px'
      });
    }
  });
});

Generally it works, in the sense that it stands where it should be and it stops scrolling where it should, however with further scrolling it just keeps flickering between the fixed point and just scrolling up, and I don't really know how to stop that. 通常,它可以正常工作,在某种意义上它应该停留在原处,并且它会停止在应有的位置滚动,但是如果进一步滚动,它只会在固定点之间不断闪烁,而只是向上滚动,而我真的不知道如何停止。

you can use these functions: 您可以使用以下功能:

function disableScroll() {
  if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
  window.onwheel = preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
  window.ontouchmove  = preventDefault; // mobile
  document.onkeydown  = preventDefaultForScrollKeys;
}

    function enableScroll() {
        if (window.removeEventListener)
            window.removeEventListener('DOMMouseScroll', preventDefault, false);
        window.onmousewheel = document.onmousewheel = null; 
        window.onwheel = null; 
        window.ontouchmove = null;  
        document.onkeydown = null;  
    }

 $(document).ready(function() {
  var distance = absToFix();
  $(window).scroll(function() {
    distance = absToFix();
    if (distance < 220) {
      disableScroll();
    } else {
      $('#sidebar').css({
        position: 'absolute',
        top: '340px'
      });
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM