简体   繁体   English

jQuery-在没有固定位置的情况下滚动窗口时防止滚动元素

[英]jQuery - Prevent scroll element when window scrolled without fix position

I want to ask about prevent scroll element. 我想问一下防止滚动元素。 I have an element that automatically scrolled when window scrolled and all website have that, because this is default. 我有一个在窗口滚动时会自动滚动的元素,并且所有网站都具有该元素,因为这是默认设置。 All element can scrolled when window scrolled, right ? 窗口滚动时所有元素都可以滚动,对吗? Now, i want to prevent that automatically scroll on element when window scrolled, but i not want set that element position to fixed. 现在,我想防止在窗口滚动时自动在元素上滚动,但是我不想将该元素位置设置为固定。 How i can do that ? 我该怎么做? Any idea ? 任何想法 ?

For example : 例如 :

    $(window).scroll(function(){
      if($(this).scrollTop() == 100){
        $(element) // How to prevent scroll this element without position fixed ?
      }
   });

There is a new CSS3 position attribute called position:sticky - which when applied (you add the offset as a data attribute). 有一个名为position:sticky的新CSS3位置属性-在应用时(您将偏移量添加为数据属性)。

Link from the dev notes https://developer.mozilla.org/en-US/docs/Web/CSS/position 开发人员笔记的链接https://developer.mozilla.org/en-US/docs/Web/CSS/position

Link from CSS tricks https://css-tricks.com/position-sticky-2/ 来自CSS技巧的链接https://css-tricks.com/position-sticky-2/

So basically when you scroll past the offset - the element is "sticky". 因此,基本上,当您滚动经过偏移量时-元素为“粘性”。 This achieves the same effect as applying the position:fixed style rule but without rewriting the DOM. 这可达到与应用position:fixed样式规则相同的效果,但无需重写DOM。

It suffers from the same issue as position:fixed however in that you need to apply padding to the body when the element is "stuck" since it takes it out of the page flow and all elements will sit higher in the page since the element is no longer calculated in height. 它具有与position相同的问题:但是已修复,因为当元素“卡住”时,您需要在主体上应用填充,因为它将其带出页面流,并且所有元素在页面中的位置都较高,因为该元素是不再计算高度。

But the upshot is that you can apply the sticky class without javascript / jquery and without hte cost of the scroll lisener on the page. 但是结果是,您可以在没有javascript / jquery的情况下应用sticky类,并且无需在页面上花费滚动lisener的开销。

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

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