元素点击页面顶部时添加类,当元素到达父元素底部时删除类

时间:2013-10-31 17:57:22

标签: jquery scroll offset scrolltop sticky

我想要实现的目标:

  • 当图像顶部到达窗口顶部(通过滚动)时,元素“粘性”将添加到元素
  • 当现在粘贴的图像到达其容器的底部时,该类将被删除,并且该元素将保持在最后一个底部位置
  • 当用户向上移动时,会发生相同的过程,只从底部开始,到达顶部。

Fiddle

相关jQuery

$(".entry-thumbnail").each(function () {
    var $this = $(this),
        p = $this.parent(),
        scrollT = $this.scrollTop(),
        scrollW = $(window).scrollTop(),
        scrollPT = p.scrollTop() + p.outerHeight();

    if (!$this.hasClass("sticky")) {
        console.log("Tada!");
        $(window).scroll(function () {
            if (scrollT <= scrollW) {
                $this.addClass("sticky");
            }
        });
    }
    else {
       $(window).scroll(function () {
            if (scrollT + $this.outerHeight() >= scrollPT) {
                $this.removeClass("sticky");
            }
        });
    }
});

我遇到的问题:

  • 将类添加到所有元素
  • 添加班级
  • 时,元素位置(左/右)会发生变化
  • 类不会被删除

1 个答案:

答案 0 :(得分:2)

我对你的问题采取了不同的方法。我计算window.scroll事件处理程序中所需的绝对高度,然后根据滚动高度将高度设置为适当的文章。

检查演示http://jsfiddle.net/eh3sT/并告诉我它是否适合您。

修改:您自己修复了大部分问题。谢谢:)

我认为没有太多优化,但我只是修改了一点以提高可读性。查看http://jsfiddle.net/eh3sT/3/embedded/result/

上的完整演示

完整代码:

var etPos = []
var $articles = $("article");
$articles.each(function () {
    var tPos = $(this).offset();
    etPos.push([tPos.top, tPos.top + $(this).height(), $(this).find('.entry-thumbnail').height()]);
});

$(window).scroll(function () {
    var scrollHeight = $(document).scrollTop();
    var cssProp = {};
    for (var i = 0; i < etPos.length; i++) {
        var $atricle = $articles.eq(i);
        if (scrollHeight >= (etPos[i][0]) && scrollHeight <= (etPos[i][1] - etPos[i][2] - 20)) {
            cssProp.top = scrollHeight - etPos[i][0] + 10;
            cssProp.bottome = "auto";
        } else if (scrollHeight > (etPos[i][1] - etPos[i][2] - 20) && $atricle.height() > ($atricle.find('.entry-thumbnail').height() + 10)) {
            /*
            Remove the second condition if the article height is always > respective thumbnail + 10. we don't want set bottom 10, if the thumbnail has no space to scroll.
            */
             cssProp.top = "auto";
             cssProp.bottom = 10;
        }else {
            cssProp.top = 10;
            cssProp.bottom = "auto";
        }
        $atricle.find('.entry-thumbnail').css(cssProp);
    }
});

注意:为所有文章标记添加了article课程。

相关问题