如果其他类出现在滚动高度,则删除该类

Remove class if other class present at scroll height

本文关键字:删除 高度 其他 如果 滚动      更新时间:2023-09-26

我需要在滚动中隐藏一个元素,但前提是它还没有隐藏。

我已经写了以下jQuery,但由于某种原因它不起作用——有什么建议吗?

css类open-style-switcherclose-style-switcher确定了css滚动动画。我想等到页面滚动到一定的高度,然后自动隐藏搜索框,如果它包含打开的类。

我哪里错了!?

  $(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        $('#search-box').hasClass('open-style-switcher').toggleClass("open-style-switcher", "close-style-switcher", 1000);
    }
});

"toggleClass"可以接收两个用空格分隔的类
还创建了"$searchBox"变量,以避免在DOM中进行双重搜索
如前所述:hasClass()返回布尔值
这是:

 $(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        var $searchBox = $('#search-box');
        if ($searchBox.hasClass('open-style-switcher'))
        {
             $searchBox.toggleClass("open-style-switcher close-style-switcher", 1000);
        }
    }
});

.hasClass()-Returns: Boolean确定是否有任何匹配的元素被分配给给定的类。

在您的场景中,addClassremoveClass更合适。

见下文:

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  var searchbox = $('#search-box');
  if (scroll >= 500 && searchbox.hasClass('open-style-switcher')) {
    searchbox.removeClass("open-style-switcher");
    searchbox.addClass("close-style-switcher", 1000);
  }
});

toggleClass()不会以您甚至其他答案认为的方式工作。它只是添加和删除类,而不是将它们交换给其他类。请参阅此处的toggleClass()文档。

if (scroll >= 500) {
    if($('#search-box').hasClass('open-style-switcher'))
    {
       $('#search-box').removeClass("open-style-switcher");
       $('#search-box').addClass("close-style-switcher");
    }
}

我想你也会想要一个与此相反的其他块。也许下面是一种更直接的方法来实现您想要实现的目标,因为检查#search-box是否已经具有open-style-switcher类可能没有任何意义。

if (scroll >= 500) {
    $('#search-box').removeClass("open-style-switcher").addClass("close-style-switcher");
}
else
{
    $('#search-box').removeClass("close-style-switcher").addClass("open-style-switcher");
}