首页 > 解决方案 > 如何使用javascript添加或删除li第一个孩子的类

问题描述

我想将 jquery 代码转换为 javascript,其中当窗口高度小于 50 时,添加或删除未在 li 第一个子级上添加的类,但添加或删除了其他 li 子类。在下面显示 jquery 代码

  $(window).scroll(function(){
      if ($(window).scrollTop() >=50) {
        $('.responsive-header .social-icons .social-icon li').not(':first-child').addClass('hidden');
        $('.responsive-header .social-icons .social-icon li').not(':first-child').removeClass('show');
      }
   });

标签: javascriptjquery

解决方案


window.onscroll = function(e) {
    if (e.target.scrollHeight > 50) {
        document.querySelectorAll(".responsive - header.social - icons.social - icon li:not(:first-child)").forEach(function (el) {
            el.classList.add('hidden');
            el.classList.remove('show');
        }) 
    }
};

我没有测试它,但想法是这样的


推荐阅读