jQuery - DIV to move with scrolling motion and stick position to top and bottom of window

*爱你&永不变心* 提交于 2019-11-28 23:51:06

See the fiddle here: http://jsfiddle.net/dKDJz/2/

Basically, you just watch for scroll events, and once the the window's scroll offset is greater than the top of the sidebar, it adds a fixed class to the sidebar, and removes when it's scrolled back up.

This was adapted from a solution posted on CSS-Tricks

I have updated the jsfiddle http://jsfiddle.net/7ey9g/76/ with my solution.

The sidebar should remain in place at the top when the window is larger than the sidebar and fix to the bottom when the sidebar is larger.

You don't need any jQuery or javascript for this. All of this can be achieved in CSS with position: fixed.

Change your sidebar selector to the following

#sidebar {
    width: 130px;
    height: auto;
    overflow: hidden;
    background: #ffffff;
    margin: 0 auto;
    clear: right;
    padding: 8px;
    background: #e5e5e5;
    border: 2px dashed red;
    position: fixed;
    right: 35px;
}

Unfortunately I don't have enough rep to simply comment with this link, so here ya go:

http://www.derekallard.com/blog/post/conditionally-sticky-sidebar

It's a few years old, but based off the screenshots it seems to cover exactly what you need.

Try this here http://jsfiddle.net/dKDJz/8/

I've removed quite a bit of the code.

Is what I have done is that when you scroll down and it reaches the top of the sidebar it sticks to the top of the window. Once you scroll back to the top it will unstick if it meets the header no matter how tall the header becomes.

I have played around with what Derek was doing, and I've accomplished the top and bottom being how you originally asked for.

I've edited some of the css for my needs, I'm sure you can just keep your old stuff in there and copy the script.

http://jsfiddle.net/mLdnb/3/

/* NewEdit */

I have replaced what I did with what you have. I came up with this:
http://jsfiddle.net/stillb4llin/dKDJz/47/

/* EndEdit */

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