jQuery在'X'视口高度滚动后添加CSS类 [英] Jquery add CSS class after 'X' amount of viewport height scrolled

查看:59
本文介绍了jQuery在'X'视口高度滚动后添加CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个jQuery函数,可以在滚动600px的视口高度后向元素添加/删除CSS类.

So I have this jQuery function that adds / removes a CSS class to an element after 600px of the viewport height has been scrolled.

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();    
    if (scroll >= 600) {
        $(".cta_box").addClass('fadeout');
    } else {
        $(".cta_box").removeClass('fadeout');
    }
});

我想对其进行调整,因此它不是基于像素值来工作,而是基于视图高度css测量值"VH"来工作,但是在这种情况下,等效的结果很重要.

I'd like to tweak it so instead of working based off a pixel value, it works off of the view height css measurement "VH", but the equivalent results are what matter in this case.

推荐答案

可以通过使用$(window).height()获取window高度来完成.

It can be done by getting the window height using $(window).height().

例如,假设您必须多滚动一半屏幕(高度为150vh),并且必须检测何时滚动了40%:

For instance suppose you have to scroll half the screen more (height is 150vh) and you have to detect when 40% has been scrolled:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();    
    if (scroll >= 0.4 * $(window).height()) {
        $(".cta_box").addClass('fadeout');
    } else {
        $(".cta_box").removeClass('fadeout');
    }
});

body{
  margin: 0;
  height: 150vh;
}
.cta_box {
  height: 100%;
  background: green;
}
.cta_box.fadeout {
  background: grey;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="cta_box"></div>

这篇关于jQuery在'X'视口高度滚动后添加CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆