简体   繁体   English

JS滚动添加类

[英]JS Add Class On Scroll

– – – – – Update – – – – – – – – – –更新– – – – –

Hi there, I have replaced the following code if (isScrolledIntoView(this) === true) { with this code if (scroll >= 500) { but the class is no longer being added. 嗨,我已经将以下代码if (isScrolledIntoView(this) === true) {替换为以下代码if (isScrolledIntoView(this) === true) { if (scroll >= 500) {但不再添加该类。 Also, wouldn't 500 be a pixel value as opposed to a percentage of the viewport height? 另外,不是500是像素值,而是视口高度的百分比吗? Also, would this solution help with my first issue described below? 另外,此解决方案对下面所述的第一个问题有所帮助吗?

If I should have put these two queries in two separate questions, please let me know. 如果我应该将这两个查询放在两个单独的问题中,请告诉我。 I've only every posted single issue queries in the past. 我过去只发布过每一个问题。

Thanks. 谢谢。

– – – – – End Update – – – – – – – – – –最终更新– – – – –

Looking for a bit of Javascript help, I'm currently adding a class to an element when it's scrolled into view but am having a couple of issues. 在寻找一些Javascript帮助时,我目前正在将元素滚动到视图中时将其添加到元素中,但遇到了一些问题。

The first issue is that when the element is vertically larger than the viewport height, the class does not get added. 第一个问题是,当元素垂直大于视口高度时,不会添加该类。

The second issue is that the class is getting added when the element is halfway down the page, I'm looking to find out if there is a way to add the class when is element is scrolled into view further up the page? 第二个问题是,当元素位于页面中途下方时,该类将被添加,我正在寻找是否有一种方法可以在元素被滚动到页面上方的视图中时添加该类? Ideally I'd like to specify this value as a percentage of the viewport height as the site I'm building is responsive. 理想情况下,由于要构建的网站具有响应能力,因此我希望将此值指定为视口高度的百分比。 Is this possible? 这可能吗?

$(window).scroll(function () {
    $('.fade').each(function () {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('fadeInTransition')
        }
        else{
            //$(this).removeClass('fadeIn')
        }
    });
});
function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

Thanks for your time 谢谢你的时间

Barry 巴里

This has been already addressed: 这已经解决:

Add/remove class with jquery based on vertical scroll? 添加/删除基于垂直滚动的jQuery类?

just simply replace 500 with your estimate 只需用您的估计值替换500

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM