简体   繁体   English

滚动时如何在视口中滑动元素?

[英]How to make an element slide with the viewport as it scrolls?

I've Googled for this but must be using the wrong keywords. 我已经为此进行了Google搜索,但必须使用错误的关键字。

Basically I want to use the effect that Magento and now Stack Overflow uses. 基本上,我想使用Magento和现在Stack Overflow使用的效果。 That is, there is an element in a column, and when you scroll down, it sticks to the top of the viewport. 也就是说,一列中有一个元素,当您向下滚动时,它会停留在视口的顶部。 And once scrolled up again, it goes back into the normal page flow. 再次向上滚动后,它将返回正常的页面流。

This Ask A Question is a good page for example. 例如,此“提问”是一个很好的页面。 Scroll down and watch the "How to Format" element come down (might need to make your viewport smaller if you have a large screen to see the effect). 向下滚动并观看“ How to Format”元素的下降(如果您有大屏幕才能看到效果,则可能需要缩小视口)。

I've noticed it is setting position: fixed in the CSS. 我注意到它正在设置position: fixed在CSS中已position: fixed The JavaScript however is obfuscated. 但是,JavaScript被混淆了。

What's the easiest way to achieve this effect? 实现此效果的最简单方法是什么? Is there a jQuery plugin available? 有可用的jQuery插件吗?

I noticed google doing this in certain places, like here http://news.google.com/nwshp?hl=en (the left side navigation bar). 我注意到Google在某些地方这样做,例如http://news.google.com/nwshp?hl=zh-CN (左侧导航栏)。 From what I can tell, they checking the position on the page and then setting the item to a fixed position once the page is scrolled down enough for the element to start scrolling off the screen. 据我所知,他们会检查页面上的位置,然后在页面向下滚动足以使元素开始在屏幕外滚动时将项目设置为固定位置。

It looks like the other method, using jQuery to set the top margin will allow the element to lag behind and get choppy (if you don't use animation) since the javascript must continue to position the element. 看起来与另一种方法类似,使用jQuery设置顶部边距将允许元素滞后并变得断断续续(如果您不使用动画),因为javascript必须继续定位元素。

Here is an example in Ext, it would probably help a lot if I didn't have the select in the event handler, but it works. 这是Ext中的一个示例,如果我在事件处理程序中没有select的话,可能会很有帮助,但是它可以工作。

Ext.fly(document).on("scroll", function(e,t,o){
    Ext.select(".pinnable").each(function(el,c,idx){
        var y = window.scrollY;
        if(!el.hasClass("pinned")){
            var ypos = el.getY();
            if(y>ypos){
                el.addClass("pinned");
                el.set({
                    originalY:ypos
                });
            }                   
        } else {
            var origy = el.getAttribute("originalY");
            if(origy && y<origy){
                el.removeClass("pinned")
            }
        }
    });     
});

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

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