滚动元素后去除粘性 [英] Remove stickiness after scrolling element

查看:46
本文介绍了滚动元素后去除粘性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在滚动几个像素后使某些元素发粘是非常简单的.但是,您将如何做相反的事情?

It is pretty simple to make some element sticky after scrolling several pixels. However, how would you do an opposite of that?

我希望某个元素具有粘性,但是例如在滚动后400px(恢复到原始位置).

I want an element to be sticky, but after scrolling e.g. 400px (to its original position) it would remain there.

可以在此处找到一个很好的示例 http://ultrahd-3d-televize.heureka.cz

A very good example can be found here http://ultrahd-3d-televize.heureka.cz

推荐答案

我花了一些时间来写我的答案,因为我利用这次机会来学习debouncing,以防止检查的那段代码每次滚动完成后,scroll都会被调用(理论上,浏览器会泛滥).

It took a while for me to write my answer, because I used the opportunity to learn about debouncing, to prevent that the piece of code that checks on scroll gets called every time one scroll is done (in theory flooding your browser).

JSFIDDLE

我的jQuery:

var menuHeight = $('.menu').height();
console.log(menuHeight);

var scrollingMachine = debounce(function() {
  var $this = $(this);

  if($(document).scrollTop() > (menuHeight - 850)) {
        console.log($(document).scrollTop() - 850);
        $('.stickypart').addClass('absolute');
    }
    else {
        $('.stickypart').removeClass('absolute');
    }
}, 100);

window.addEventListener('scroll', scrollingMachine);

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

去抖仅在滚动停止后才调用该函数,每100ms最多进行一次. (如果希望更快地反应,只需将100更改为其他名称即可.)

Debouncing helps by only calling the function after the scrolling stops, with a maximum of once every 100ms. (just change the 100 to something else if you want it to react faster).

最好对所有在滚动或调整大小时触发的功能进行去抖动,以防止浏览器计算滚动或调整大小的每个像素,并且仅在用户完成滚动或调整大小时才触发.它也可以用于键入或AJAX调用的情况.特别是在AJAX调用的情况下,您只想在必要时才触发功能,而不是在用户从字母上抬起手指时才触发.在此处查看示例.

It's a good idea to debounce all functions that get triggered on scroll or for example resizing, to prevent the browser from calculating for every pixel scrolled or resized and only firing when the user is done scrolling or resizing. It can also be used in the case of typing or AJAX calls. Especially in the case of AJAX calls, you want to only fire a function when necessary, not whenever the user lifts his finger from a letter. See an example here.

这篇关于滚动元素后去除粘性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆