如果y-position大于另一个元素,则将类添加到元素

时间:2017-04-21 08:35:45

标签: javascript jquery

我想在用户的滚动位置“点击”一个特殊的 - 其他 - 元素时,为一个元素添加一个类。

我尝试使用该代码

var hands = $(".sw_3--breit");
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
// The next line is the one I am asking for help
       if (scroll >= window.innerHeight) 
       {
          hands.addClass("fixed");
        } else {
          hands.removeClass("fixed");
        }
});

通过在滚动大于用户显示高度之后添加类,这是很好的。但是我想添加 - 然后还删除 - 一个类,然后用户“击中”另一个元素。

我所要求的是 - 我知道非常粗略和愚蠢 - 比如:

var other_elements_position = $(".other_element"().position;
if (scroll >= other_elements_position) 

我怎样才能实现这一目标?而且我已经将jquery用于其他事情了,所以使用jquery就可以了。我想是的。

谢谢!

1 个答案:

答案 0 :(得分:0)

对于遇到与我相同问题的人来说,这对我有用:

var hands = $(".sw_3--breit");
var hands_original = $(".sw_8").position();
var hands_off = $("#target_agentur").position();
var hands_corrected = (hands_original.top + 680) // here I add a small delay to the trigger of the "animation"
$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    if (scroll >= hands_corrected && scroll <= hands_off.top) // I doublecheck against 2 heights
{
        hands.addClass("fixed");
    } else {
        hands.removeClass("fixed");
    }
});
相关问题