简体   繁体   English

滚动时使元素停留在顶部

[英]Make element stick to top when scrolling

I've written a function to make a div element stick to top when scrolling. 我编写了一个函数,使div元素在滚动时保持顶部。

it works when it's written like this('#sticky-anchor-for-social' is to detect moving distance of the element, '#social-media' is the element sticks): 它的工作原理是这样写的(“#sticky-anchor-for-social”用于检测元素的移动距离,“#social-media”是元素粘贴):

function sticky_socialmedia() {
    var window_top = $(window).scrollTop();
    var social_top = $('#sticky-anchor-for-social').offset().top - 88;
    if (window_top >= social_top) {
       $('#social-media').addClass('stick-social');
    } else {
       $('#social-media').removeClass('stick-social');
    }
}

$(window).scroll(sticky_socialmedia);
sticky_socialmedia();

but it doesn't work when I write it like this: 但是当我这样写时它不起作用:

function stickyWhenScroll(anchor, sticky) {
    var window_top = $(window).scrollTop();
    var filter_top = $(anchor).offset().top - 88;
    if (window_top >= filter_top) {
       $(sticky).addClass('stick-filter');
    } else {
       $(sticky).removeClass('stick-filter');
    }
 }

 $(window).scroll(stickyWhenScroll);
 stickyWhenScroll('#sticky-anchor-for-social','#social-media');

what could possibly go wrong? 可能出什么问题了? many thanks! 非常感谢!

You need to send your parameters to your function when adding the event, you can do that with bind : 添加事件时,需要将参数发送给函数,可以使用bind

$(window).bind('scroll', {
    anchor: '#sticky-anchor-for-social', 
    sticky: '#social-media'
}, stickyWhenScroll).trigger('scroll');

By passing trigger('scroll') you can trigger the function straight away. 通过传递trigger('scroll')您可以立即触发函数。

And in your function you can retrieve them by accesing the event.data : 在您的函数中,您可以通过添加event.data来检索它们:

function stickyWhenScroll(event) {
    var data = event.data;
    var anchor = data.anchor;
    var sticky = data.sticky;
    ...
}

Fiddle 小提琴

Because in your 2nd snippet the scroll event handler hasn't received any params. 因为在您的第二个片段中,滚动事件处理程序尚未收到任何参数。 You could either pass params both times (load and scroll) or declare those as global variables and use them within the function. 您可以同时传递参数(加载和滚动),也可以将它们声明为全局变量,然后在函数中使用它们。

(function stickyWhenScroll(anchor, sticky) {
    var window_top = $(window).scrollTop();
    var filter_top = $(anchor).offset().top - 88;
    if (window_top >= filter_top) {
        $(sticky).addClass('stick-filter');
    } else {
        $(sticky).removeClass('stick-filter');
    }
}('#sticky-anchor-for-social', '#social-media'));

$(window).scroll(function() {
    stickyWhenScroll('#sticky-anchor-for-social','#social-media');
});

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

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