一旦它的全高度滚动过去,如何修复div?

时间:2015-07-08 14:08:15

标签: javascript jquery

我有一个侧边栏,我想成为位置:固定;并且只有在整个div滚动过去之后才会紧贴屏幕的底部。

div需要像往常一样滚动相对于它的父级,然后在该div的底部与浏览器窗口的底部相遇时变为固定。我正在努力实现像this一样的侧边栏。

我遇到了一个在线的JS,我已经把它包含在我的Demo中但是对JS不太好我甚至不确定我是否正在做正确的事情&似乎无法让它发挥作用。

$(document).ready(function() {
    var s = $(".sidebar");
    var pos = s.offset().top+s.height(); //offset that you need is actually the div's top offset + it's height
    $(window).scroll(function() {
    var windowpos = $(window).scrollTop(); //current scroll position of the window
    var windowheight = $(window).height(); //window height
    if (windowpos+windowheight>pos) s.addClass('stick'); //Currently visible part of the window > greater than div offset + div height, add class
        else s.removeClass('stick');
    });
});

更新:我需要js来检测整个元素何时处于视图中,然后从底部修复它。或者更准确地说,当元素的底部碰到窗口的底部时。

任何帮助或指导都将不胜感激。

2 个答案:

答案 0 :(得分:0)

就像我说的那样,你正朝着正确的方向前进。 我对你的js和css做了一些小修改

JsFiddle Here

js code:

import Data.List

triangles :: [Int]
triangles = takeWhile (\n -> factors n /= 0) [n * (n + 1) `div` 2 | n <- [1..]]
triangles' = takeWhile (/= 0) [n * (n + 1) `div` 2 | n <- [1..]]

intSqrt :: Int -> Int 
intSqrt = floor . sqrt . fromIntegral

factors :: Int -> Int 
factors n = 2 * length facs
    where facs = takeWhile (<= intSqrt n) [x | x <- [1..], n `mod` x == 0]

答案 1 :(得分:0)

是这样的吗? JSFiddle

代码:

$(document).ready(function() {
    var h = $(".header");
    var s = $(".sidebar");
    var f = $(".footer");
    var startat = h.offset().top+h.height();
    s.css({top: startat+"px",height: s.height()+"px"});
    var pos = s.offset().top+s.height(); //offset that you need is actually the div's top offset + it's height
    var endat = f.offset().top;

    $(window).scroll(function() {
        var endat = f.offset().top;
        var footer_height = f.height();
        var windowpos = $(window).scrollTop(); //current scroll position of the window
        var windowheight = $(window).height(); //window height

        if ((windowpos+windowheight)>pos && (windowpos+windowheight)<endat){
            s.css({top: "",height: ""});
            s.addClass("stick").removeClass("reston");
            s.css({bottom: ""});
        } else if((windowpos+windowheight)>endat){
            s.css({bottom: footer_height+"px"});
        }
        else {
            s.css({top: startat+"px",height: s.height()+"px"});
            s.removeClass("stick").addClass("reston");
            s.css({bottom: ""});
        }
    });
});

你可以添加一些像动画这样的CSS来平滑滚动效果边栏。

或直接使用top position属性并按下scrollTop并在“footer”之前等待“else if”

最好的问候