代码之家  ›  专栏  ›  技术社区  ›  user3108268

仅在滚动中预结束一次

  •  0
  • user3108268  · 技术社区  · 4 年前

    如果类存在,则仅在scroll上预先添加元素一次。如果类不存在,请删除。

    例如向下滚动->类被添加+前置。向上滚动->类被删除,所以是prepend等等。

    $(window).scroll(function() {
    if($("#container").hasClass("active")){
         $("#container-wrapper").addClass("active-exists");
         $("#container-wrapper").prepend("<p>Test</p>");
    }
    else {
         $("#container-wrapper").removeClass("active-exists");
         $("#container-wrapper").remove("<p>Test</p>");
    }
    

    });

    当前的行为不断增加无限 <p>Test</p> 不停,只需在上下滚动时对其进行垃圾邮件处理。

    2 回复  |  直到 4 年前
        1
  •  1
  •   Spectric amamoto    4 年前

    检查y轴滚动位置是否为0,而不是检查元素是否具有特定类。您还需要存储是否已将元素追加到变量中,以免继续追加到scroll中。

    let elem = $('<p>Test</p>')
    var hasAdded = false;
    $(window).scroll(function() {
      const scrollY = window.scrollY;
      if (scrollY == 0) {
        $('#container-wrapper').removeClass('active-exists')
        elem.remove()
        hasAdded = false;
      } else {
        if (!hasAdded) {
          $('#container-wrapper').addClass('active-exists').prepend(elem)
          hasAdded = true
        }
      }
    });
    html,
    body {
      height: 300%;
    }
    
    #container-wrapper{
      position:fixed;
      height:50px;
    }
    
    .active-exists{
      background-color:yellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="container-wrapper">
      <div id="container">
    
      </div>
    </div>
        2
  •  1
  •   subodhkalika    4 年前

    您可以通过标记“追加”来检查这一点

    window.appended = false; // set as global variable
    $(window).scroll(function() {
       if($("#container").hasClass("active")){
            $("#container-wrapper").addClass("active-exists");
            if (!window.appended){   // check with global variable
                 $("#container-wrapper").prepend("<p>Test</p>");
                 appended = true;
            }
               
       }
       else {
            $("#container-wrapper").removeClass("active-exists");
            $("#container-wrapper").remove("<p>Test</p>");
        }
    }