Fixing a menu in one direction in jquery

╄→尐↘猪︶ㄣ 提交于 2019-12-01 09:39:16

I think I just came up with a great solution for this problem, so I'm going to post it here in case others are also looking for something.

To recap, my problem was that I wanted a left menu to be fixed vertically, so it follows the vertical scroll, but not fixed horizontally. css only allows fixing in both directions. So with the css solution, when the window was small, a horizontal scrollbar would appear, and when used, it would cause the menu to float over the page content.

The float_vertical_scroll function which I presented as another solution in the initial question had the flaw that when you scrolled vertically, javascript would refresh too slowly, causing the menu bar to move in a jumpy, choppy fashion. That solution set the position to absolute, and relied on jquery to move the menu down on every scroll event.

The thing about sidebar menus on most pages is that 99% of scrolling is vertical. Very little is horizontal. So I thought, what if we could make the horizontal scrolling choppy, and the vertical scrolling smooth?

That led to the solution below. Instead of setting the frame to absolute and scrolling it vertically in javascript, I've set it to fixed, and reversed the offset on horizontal scrolling. This cancels out the horizontal scrolling. Horizontal scrolling might be a bit jumpy, but no one really cares because it's rarely used:

function float_horizontal_scroll(id) {
    jQuery(window).scroll(function(){
        jQuery(id).css({
            'left': 0 - jQuery(this).scrollLeft()
        });
    });
}

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