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

天涯浪子 提交于 2020-01-23 20:44:08

问题


I've Googled for this but must be using the wrong keywords.

Basically I want to use the effect that Magento and now Stack Overflow uses. 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).

I've noticed it is setting position: fixed in the CSS. The JavaScript however is obfuscated.

What's the easiest way to achieve this effect? Is there a jQuery plugin available?


回答1:


Here is an article that should help: http://www.wduffy.co.uk/blog/keep-element-in-view-while-scrolling-using-jquery/comment-page-1/




回答2:


I noticed google doing this in certain places, like here http://news.google.com/nwshp?hl=en (the left side navigation bar). 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.

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.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")
            }
        }
    });     
});


来源:https://stackoverflow.com/questions/2458969/how-to-make-an-element-slide-with-the-viewport-as-it-scrolls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!